Reputation: 2825
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?
Upvotes: 6
Views: 2450
Reputation: 67743
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.
Upvotes: 4
Reputation: 214060
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.
Upvotes: 15
Reputation: 820
The MSVC version of this C-API function sets errno
.
See https://msdn.microsoft.com/en-us/library/we1whae7%28v=vs.100%29.aspx.
Upvotes: 2