Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if free worked

Tags:

c

malloc

free

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".

like image 637
Blue Granny Avatar asked Dec 06 '16 15:12

Blue Granny


2 Answers

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 by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, 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.

like image 138
dbush Avatar answered Sep 27 '22 19:09

dbush


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.

like image 24
Sergey Kalinichenko Avatar answered Sep 27 '22 21:09

Sergey Kalinichenko