Is this acceptable using malloc and free? (WITH)

I am currently learning C. My teacher gave this as a bad example of using malloc and for free, but for me it looks good. 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 releasing p1 and * p2 will lead to "undefined" behavior, but I don't understand why.

I understand that double freeing the same area in memory is bad, but * p2 will not point to a pointer indicating where is 7? I think he meant to do free (p1) and free (** p2) badly. I'm right?

+4
source share
1 answer

, . , malloc 0x10, malloc 0x30. , :

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

free(p1) :

enter image description here

, p1 *p2 , . , free(*p2) , . free(p2) 0x30.

+8

Source: https://habr.com/ru/post/1668142/


All Articles