Is there a way to test that a pointer's memory allocation has been freed?
Is there a way to tell that a pointer's memory assignmen开发者_运维问答t has been deallocated? I am just starting out in C and I think I am finally starting to understand the intricacies of memory management in C.
So for example:
char* pointer;
pointer = malloc(1024);
/* do stuff */
free(pointer);
/* test memory allocation after this point */
I know that the pointer will still store the memory address until I set pointer = NULL
- but is there a way to test that the pointer no longer references memory I can use, without having to set it to NULL first?
The reason I want to do this is that I have a bunch of unit tests for my C program, and one of them ensures that there are no orphaned pointers after I call a special function which performs a cleanup of a couple of linked lists. Looking at the debugger I can see that my cleanup function is working, but I would like a way to test the pointers so I can wrap them in a unit test assertion.
There is no standardized memory management that tells you whether or not any given address is part of a currently allocated memory block.
For the purposes of a unit test, you could create a global map that keeps track of every allocation, so you make every allocation go through your custom malloc
function that adds an entry to the map in debug builds and removes it again in free
.
You could always link against an instrumented version of the libraries (say electric fence) for the purposes of unit testing.
Not ideal because you introduce a difference in the production and testing environments.
And some systems may provide sufficient instrumentation in their version of the standard library. For instance the Mac OS 10.5 library supports calling abort (3)
on double frees, so if your unit tester can trap signals you are home free.
Shameless and pointless self promotion: my little toy c unit testing framework can trap signals.
Neither standard C nor POSIX (I think) provides a way to check that. Your specific operating system might have some sort of elaborate black magic for doing this that is only revealed to the Inner Circle of System Programmers, though.
Use good c practices. Example:
char* pointer = NULL;
/* do stuff */
pointer = malloc(1024);/* malloc does not always work, check it. */
if(pointer == NULL) {
/*Help me, warn or exit*/
}
/* do stuff */
if(pointer) {
free(pointer);
pointer = NULL;
}
/* do stuff */
if(pointer) {
/* tested memory allocation stuff */
}
Longer, yes, but if you always set a freed pointer to NULL, it's easy to test.
精彩评论