Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free a pointer equal to a malloc pointer

Tags:

c

I'm having trouble understanding some of the free() behavior.

int* ptr1 = (int*)malloc(sizeof (int)*10);
int* ptr2 = ptr1;
free(ptr2);

Is the free(ptr2) going to delete my array as I want ?

What if I do :

int** ptr1 = (int**)malloc(sizeof (int)*10);
int* ptr2 = (int*)malloc(sizeof (int));
*ptr2 = 10;
ptr1[0] = ptr2;
free(ptr1);

Is this code correct ? Will free(ptr1) will also delete the space of ptr2 ?

Thanks

like image 829
M-Gregoire Avatar asked Dec 25 '22 06:12

M-Gregoire


1 Answers

int* ptr1 = (int*)malloc(sizeof(int)*10);
int* ptr2 = ptr1;
free(ptr2);

That is fine, ptr2 contains the same value as ptr1, and thus the memory you passed to malloc() is free()d.

int** ptr1 = (int**)malloc(sizeof(int)*10);
int* ptr2 = (int*)malloc(sizeof(int));
*ptr2=10;
ptr1[0]=ptr2;
free(ptr1);

That is not fine. You are storing the value of ptr2 in the ptr1 array, but not freeing it. You want:

int** ptr1 = (int**)malloc(sizeof(int*)*10);
int* ptr2 = (int*)malloc(sizeof(int));
*ptr2=10;
ptr1[0]=ptr2; 
...
free(ptr1[0]);
free(ptr1);

Note I have also changed the malloc() to allocate 10 pointers to int, not merely ten ints (which may not be the same size).

Finally note that you don't need to cast the return value from malloc() in C. I haven't fixed that for you as it is not a problem in itself and is unrelated to your question, but it is (arguably) bad style.

like image 82
abligh Avatar answered Jan 05 '23 17:01

abligh