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;
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With