Using freed memory

If you attempt to read or write to memory that was previously freed, the result will be a conflict and the program will generate a memory error. For example, if a program calls the free() function for a particular block and then continues to use that block, it will create a reuse problem when a malloc() call is made.

Consequences

Using freed memory generates the following runtime errors:


Detecting the error

The Memory Analysis tool can detect only a limited number of situations where free memory is read/written with following conditions:


strcat() strdup() strncat() strcmp() strncmp() strcpy() strncpy() strlen() strchr() strrchr() index() rindex() strpbrk() strspn() strcspn() strstr() strtok() memccpy() memchr() memmove() memcpy() memcmp() memset() bcopy() bzero() bcmp()


malloc() calloc() realloc() free()

Enabling error detection

To enable error detection when using freed memory:


  1. In the Launch Configuration window, select the Tools tab.
  2. Expand Memory Errors and select the Enable error detection checkbox.
  3. To detect usage of freed memory, select Verify parameters in string and memory functions.
  4. To detect writing to a freed memory area, select Enabled bounds checking (where possible).

Message returned to the IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:


For a list of error messages returned by the Memory Analysis tool, see Summary of error messages for Memory Analysis.

How to address freed memory usage

Set the pointer of the freed memory to NULL immediately after the call to free(), unless it is a local variable that goes out of the scope in the next line of the program.

Example

The following code shows an example using already freed memory:

int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(13);
  free(ptr);
  strcpy(ptr,"Hello World!");
  return 0;
}
Related concepts
Illegal deallocation of memory
NULL pointer dereference
Buffer overflow
Reading uninitialized memory
Resource (memory) leaks
Functions checked for memory errors during memory analysis
Summary of error messages for Memory Analysis