Properly using dynamically allocated memory is another tricky issue. In many cases, programs continue running well after a programming error causes serious memory corruption; sometimes they don’t crash at all. One common mistake is to try to reuse a pointer after it has already been freed. As an example we could modify the “Hello world” program (see Pointer Abuse) to de-allocate memory blocks before allocating the larger ones. Consider the following piece of code which does just that:
if(string_so_far != (char *)0) { free(string_so_far); strcpy(string, string_so_far); } else *string = '\0';
If you run this code (hello4.c) through Insure++, you’ll get another error message about a “dangling pointer” at line 23. The term “dangling pointer” is used to mean a pointer that doesn’t point at a valid memory block anymore. In this case the block is freed at line 22 and then used in the following line. This is another common problem that often goes unnoticed, because many machines and compilers allow this particular behavior.
In addition to this error, Insure++ also detects the following errors:
- Reading from or writing to “dangling pointers."
- Passing “dangling pointers” as arguments to functions or returning them from functions.
- Freeing the same memory block multiple times.
- Attempting to free statically allocated memory.
- Freeing stack memory (local variables).
- Passing a pointer to
free
that doesn’t point to the beginning of a memory block. - Calls to
free
withNULL
or uninitialized pointers. - Passing non-sensical arguments or arguments of the wrong data type to
malloc
,calloc
,realloc
, orfree
.
Another way that Insure++ can help you track down dynamic memory problems is through the RETURN_FAILURE
error code. Normally, Insure++ will not issue an error if malloc
returns a NULL
pointer because it is out of memory. This behavior is the default, because it is assumed that the user program is already checking for, and handling, this case. If your program appears to be failing due to an unchecked return code, you can enable the RETURN_FAILURE error message class. Insure++ will then print a message whenever any system call fails.