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

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.


There is no reliable way to tell if a pointer has been freed, as Greg commented, the freed memory could be occupied by other irrelevant data and you'll get wrong result.

And indeed there is no standard way to check if a pointer is freed. That said, glibc does have functions (mcheck, mprobe) to find the malloc status of a pointer for heap consistency checking, and one of them is to see if a pointer is freed.

However, these functions are mainly used for debugging only, and they are not thread-safe. If you are not sure of the requirement, avoid these functions. Just make sure you have paired malloc/free.


Example http://ideone.com/MDJkj:

#include <stdio.h>#include <stdlib.h>#include <mcheck.h>void no_op(enum mcheck_status status) {}int main(){    mcheck(&no_op);    void* f = malloc(4);    printf("%d (should be %d)\n", mprobe(f), MCHECK_OK);    printf("%d (should be %d)\n", mprobe(f), MCHECK_OK);    free(f);    printf("%d (should be %d)\n", mprobe(f), MCHECK_FREE);    printf("%d (should be %d)\n", mprobe(f), MCHECK_FREE);    return 0;}