I am currently learning C. My lecturer gave this as a bad example of using malloc and free, but to me it seems okay. this is the code:
int *p1,**p2;
p1 = malloc(sizeof(int));
*p1 = 7;
p2 = malloc(sizeof(int*));
*p2 = p1;
free(p1);
free(*p2);
My lecturer claims that freeing p1 and *p2 will cause "undefined behavior", but I can't see why.
I understand that double freeing the same area in memory is bad but wouldn't *p2 point to a pointer that points to where 7 was? I think he meant doing free(p1) and free (**p2) is bad. Am I right?
Maybe a picture will help. Let's imagine that the first malloc returns address 0x10, and the second malloc returns address 0x30. So after the first five lines of code, the situation looks like this:

`p1` is a pointer with value `0x10`,
which points to memory that contains the integer value `7`.
`p2` is a pointer with value `0x30`,
which points to memory that contains a pointer with value `0x10` (a copy of the value in `p1`),
which points to memory that contains the integer value `7`.
After calling free(p1) you have a situation like this:

Note that both p1 and *p2 are now dangling pointers, they both point to memory that's been freed. So the line free(*p2) is not valid, you're trying to free the memory that you've already freed. Instead, you want to free(p2) to free the memory at location 0x30.
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