Understanding the concept of free

Tried the following code:

#include<stdio.h>
int main()
{        
        int *p,*q;
        p = (int *)malloc(sizeof(int));
        *p =10;
        q = p;
        printf("%u \n",p);
        printf("%u \n",q);
        free(p);
        printf("%u \n",p);
        return 0;
}

The result obtained is as follows:

[root@lnxdesk Tazim]# ./a.out
154804232
154804232
154804232

Why is this address inside p still printing, even if I did free(p);? What did free(p)you do ?

I want to clearly understand the concept of free / malloc. Any help would be helpful.

+5
source share
6 answers

free()only frees memory on the heap. It does not change the value of your pointer. If you tried to print the memory indicated by your pointer, you might get some kind of garbage.

In addition, when you called free, you pointed the pointer to it, not the address of the pointer, so freeyou cannot change the pointer ...

+5

undefined - , free d , , , - , printf() .

+3

, .. , . free 0x00, , .

, .

*p free(p), .

+2

malloc() , "", . , p , , , ( 154804232). *p = 10, 10 . q = p, q, .

free(), ilk . free(), : " ". free() , . . . , .

, . . . . , , , - , , , - . , Bad Things Happen <tm> . , .

+1

: - , . , malloc, , . , malloc(), - . , - ( , , "" ). NULL , ; , - .

0

, - . , C . , :

A free function causes a space pointed to by ptr, which should be freed, i.e. available for further distribution. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match the pointer previously returned by calloc, malloc, or realloc, or if the space was freed by a call to free or reallocate, the behavior is undefined

0
source

All Articles