malloc()
returns a null pointer if the allocation was unsuccessful. free()
unfortunately does not return whether deallocation was successful, as its signature is:
void free(void* ptr)
Is it possible to:
Attempt free()
and know whether the freeing was successful or not without the debugger crashing the app for you?
Get beforehand whether calling free()
on a pointer will result in a failure or success?
When you call free(a) it means that the memory has been flagged for re-use. So, writing an array to a will still work, but it is undefined behavior. Chances are it will be overwritten later without you being notified about it. Secondly do not cast the return value of malloc() in C.
This function does not return any value.
The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of the pointer which means it still points to the same memory location. Here is the syntax of free() in C language, void free(void *pointer_name);
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
As far as the C standard cares:
If the pointer you got returned to from malloc()
is equal to the pointer you pass to free()
, then free()
will always be successful. The only error check available is to compare the pointer with a copy of the original address, before passing it to free()
. Example:
type_t* foo = malloc(sizeof(*foo));
type_t* const original = foo;
...
if(foo == original)
{
free(foo);
}
else
{
halt_and_catch_fire();
}
If you need more advanced error handling than that, you'll have to use OS-specific API functions.
Is it possible to: ...
- Get beforehand whether calling
free()
on a pointer will result in a failure or success?
Yes! If your program is correct, free()
can only succeed. If free()
could possibly fail, your program is incorrect by definition.
I know that isn't really what you meant, but making your program statically correct is the right way forward.
To find bugs in your memory handling, you can use an error-checking malloc/free
(such as glibc gives you when running with MALLOC_CHECK_=1
- set other platforms may have their own mechanisms), or to use something like valgrind
or an address sanitizer
Note that these are logic bugs which you should then fix ... then your program will be statically correct again.
The MSVC version of this C-API function sets errno
.
See https://msdn.microsoft.com/en-us/library/we1whae7%28v=vs.100%29.aspx.
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