Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
toastedDeli Avatar asked Feb 05 '23 05:02

toastedDeli


1 Answers

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.

like image 166
user3386109 Avatar answered Mar 03 '23 17:03

user3386109