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
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 int
s (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With