Is there a way to tell that a pointer’s memory assignment 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
mallocfunction that adds an entry to the map in debug builds and removes it again infree.