How to check if a pointer is freed already in C?
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;
You can't. Just assign NULL
to it after you free
it to make sure you don't free it twice (it's ok to free(NULL)
).
Better yet, if possible don't write code where you "forget" you already freed it.
EDIT
Interpreting the question as how to find out whether the memory pointed to by a pointer is freed already: you can't do it. You have to do your own bookkeeping.