Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle free() errors in C?

Suppose that I have used a free() function to free a memory that,for many reasons, I'm not allowed to. How can I stop my C application from crashing and just generate an error and continue the execution? I don't have try-catch kind of provision here (like C++/java...). Is there any way to ignore this error and continue execution?

If yes,

  1. How do you do that?
  2. More importantly, is it advisable to do so (continuing execution considering this memory error occurred)?

Thank you

like image 221
rahman Avatar asked Jun 30 '11 05:06

rahman


People also ask

What does free () do C?

The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use.

How are errors handled in C?

As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.

What happens when free is called in C?

Call to free(c) will convert c (a char) to a pointer, and then try to free it, which will lead to system crash because (most of the time) converting a pointer to a char and back will change its value and make it an invalid pointer.

Does free return anything in C?

Return Value This function does not return any value.


2 Answers

It's certainly not advisable. Even if your program's version of free correctly detects that the memory you're trying to free cannot be freed, and thus doesn't do any harm itself, you still have a bug in your program — part of the program thought it owned that memory. Who knows what it might have tried to do with that memory before freeing it? Find and fix the bug. Don't just sweep it under the rug.

like image 119
Rob Kennedy Avatar answered Oct 13 '22 10:10

Rob Kennedy


There is nothing in the C standard that you can use to do what you want. The description of the free function is very clear on that (§7.20.3.2 in C99):

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

like image 37
Mat Avatar answered Oct 13 '22 10:10

Mat