I would like to check if a pointer is freed already or not. How do I do this using gnu compiler set?
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
You can't. Just assign
NULL
to it after youfree
it to make sure you don't free it twice (it's ok tofree(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:
You do not, since you cannot.
Keep track of pointers that you obtain from
malloc()
and only free those, and only once.If you will, memory has no memory, so it doesn't know whether it is allocated or not. Only your OS's memory manager can tell you that (but C does not include any standardized mechanism to query this information).
You can extend the concept of assigning NULL to the pointer value by writing a macro that does it for you. For example:
Then as long as you make sure your code only uses FREE() and not free(), you can be fairly confident that code you wrote doesn't free the same memory twice. Of course that does nothing to prevent multiple calls into library functions that free memory. And it does nothing to guarantee that there's a free for every malloc.
You can attempt this with a function, but it gets akward because you have to throw in a reference operator and it doesn't look like a normal call to free() anymore.
I know that this answer is
a little bit
late, but I just read this answer and wrote some code to verify the following:This code checks only if the first pointer that was allocated is freed:
I've tested this code on HP-UX and Linux Redhat and it works, for the case of only one pointer.
You can't. The way to track this would be to assign the pointer to
0
orNULL
after freeing it. However as Fred Larson mentioned, this does nothing to other pointers pointing to the same location.