I would like to check if a pointer is freed already or not. How do I do this using gnu compiler set?
Calling free() on a null pointer results in no action being taken by free() . Setting message to NULL after it is freed eliminates the possibility that the message pointer can be used to free the same memory more than once.
C standard only says that calling free twice on a pointer returned by malloc and its family function invoke undefined behavior. There is no further explanation why it is so.
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.
Freeing the allocated memory deallocates it and allows that memory to be used elsewhere while the pointer to where the memory was allocated is preserved. Setting a pointer to the allocated memory to NULL does not deallocate it.
You can't. The way to track this would be to assign the pointer to 0
or NULL
after freeing it. However as Fred Larson mentioned, this does nothing to other pointers pointing to the same location.
int* ptr = (int*)malloc(sizeof(int)); free(ptr); ptr = NULL;
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