Hi,
I'm struggling with pointers with regard to memory allocation and deallocation.
In the below code, I have two functions, f
unc() and
func2(); in
func I allocate memory using malloc and in
func2 I assign the pointer returned from func to the newly defined pointer.
So since I have allocated memory, I also have to deallocate it when done using it to avoid memory leaks. The problem is I am not sure where I have to deallocate it (well, I understand it has to be after when done with using that memory), but... where..?
I have commented out the statement where I thought it was necessary to free the memory but when executing the program I get the
"...double free or corruption (out)..." message.
Code:
#include <stdio.h>
#include <stdlib.h>
int* func(int var)
{
int *a = (int*)malloc(sizeof(int));
a = &var;
return a;
}
void func2()
{
int *b = func(5);
printf("*b = %d\n", *b);
//free(b);
}
int main()
{
func2();
return 0;
}
Can anyone please explain to me this phenomena of memory allocation/deallocation based on the above code...Do I "
free(b)" or
"free(a)" ?