toastedDeli
toastedDeli

Reputation: 580

Is this an acceptable use of malloc and free? (C)

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?

Upvotes: 4

Views: 123

Answers (1)

user3386109
user3386109

Reputation: 34829

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:

enter image description here

`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:

enter image description here

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.

Upvotes: 8

Related Questions