Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a pointer is freed already in C?

Tags:

c

pointers

free

I would like to check if a pointer is freed already or not. How do I do this using gnu compiler set?

like image 849
Kitcha Avatar asked Nov 28 '11 18:11

Kitcha


People also ask

What happens to a pointer when it is freed?

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.

What happens if you free a pointer twice in C?

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.

Is a freed pointer 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.

What is a freed pointer?

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.


1 Answers

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; 
like image 133
Chad Avatar answered Oct 06 '22 14:10

Chad