I've read this question and answer: How do malloc() and free() work?
A friend asked me how can I be sure a free worked. I replied that if it didn't work then the OS is probably crashing and it won't matter for much longer.
But I'm more interested in the nature of the answer to this question. Once I've freed memory how can I be sure it has been freed? Do I just assume it did? This is a purely theoretical question with no actual code behind it, and mostly when thinking about I decided "well it doesn't matter anyway", but I'm uneasy with this answer.
For instance if memory is a problem and I want to make sure that a large structure was freed after calling free, otherwise I'll try cleaning up again, is there a way to do this?
Edit:
To those stating my question answered here: Function free() in C isn't working for me
The answer provided there simply states that I "cannot actually test if free()
worked". I'm trying to understand why this cannot be done. What is the nature behind free.
Edit2: After reading through the answers provided it seems that the answer I gave my friend is accepted, that "it just works".
The only way free
"doesn't work" is if you pass it an invalid pointer or one that's already been freed. Doing so invokes undefined behavior.
From the man page:
The
free()
function frees the memory space pointed to byptr
, which must have been returned by a previous call tomalloc()
,calloc()
orrealloc()
. Otherwise, or iffree(ptr)
has already been called before, undefined behavior occurs. Ifptr
isNULL
, no operation is performed.
If you run your program under a memory checking tool like valgrind, it will tell you if you're calling free
incorrectly.
if memory is a problem and I want to make sure that a large structure was freed after calling free, otherwise I'll try cleaning up again, is there a way to do this?
No, there is no legal way to free the same memory twice. In fact, calling free
on a freed pointer leads to undefined behavior. That is why you should set freed pointers to NULL
if they are to remain in scope.
There is also no API to see if a memory address has been freed or not, so your code must keep track of what is currently allocated in order to free it at some later point.
You can only do so much returning the memory to the operating system: once you call free
, it's out of your hands, so you need to rely on the OS and on the memory manager of your C library to account for the freed memory correctly.
The best you can do on your side is to run your code through a memory profiler under its typical workload, and fix all errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With