Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between freeing the pointer and assigning it to NULL?

Tags:

Could somebody tell me the difference between:

int *p; p=(int*)malloc(10*sizeof(int)); free(p); 

or

int *p; p=(int*)malloc(10*sizeof(int)); p=NULL; 
like image 718
Sanjeev Kumar Dangi Avatar asked Mar 12 '10 06:03

Sanjeev Kumar Dangi


People also ask

What does freeing a null pointer do?

It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

Should I set a pointer to null after freeing it?

Dangling pointers can lead to exploitable double-free and access-freed-memory vulnerabilities. A simple yet effective way to eliminate dangling pointers and avoid many memory-related vulnerabilities is to set pointers to NULL after they are freed or to set them to another valid object.

Can you access a pointer after freeing it?

Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address.


1 Answers

free will deallocate the memory that p points to - simply assigning it to NULL will not (and thus you will have a memory leak).

It is worth mentioning that it is good practice to assign your pointer to NULL AFTER the call to free, as this will prevent you from accidentally trying to access the freed memory (which is still possible, but absolutely should not be done).

like image 194
danben Avatar answered Nov 15 '22 12:11

danben