Illegal deallocation of memory

Illegal deallocation of memory occurs when a free operation is done on a pointer that doesn't point to a valid heap block. This type of error can occur when you try to do any of the following:

Consequences

This memory problem can generate the following runtime errors:
  • memory corruption (a stack, heap, or static segment)
  • immediate segmentation fault

Detecting the error

The Memory Analysis tool detects this error if Enable check on realloc()/free() argument is checked under Memory Errors in the configuration. In this case, the illegal deallocation error is trapped when either free or realloc is called.

Information returned by the Memory Problems view

The notification for this type of memory error includes the following details:
  • Severity: ERROR
  • Description: pointer does not point to heap area
  • Pointer: address of bad pointer (typically 0 for most messages)
  • Trap Function: free or realloc
  • Alloc Kind: how memory was allocated for this block (malloc, calloc, or realloc)
  • Location: source file and line of code where the error occurred (e.g., main.c:59)
  • Count: number of blocks involved

How to address illegal deallocation of memory

To address this memory problem, try the following:
  • Avoid freeing stack and static memory by ensuring that the same pointer can never point to different memory types.
  • Never reassign an allocated pointer (except for a NULL or for performing another allocation). If you need to iterate over allocated memory, use another pointer (i.e., an alias) or an index.
  • Nullify the pointer immediately after deallocation, unless it's a local variable that's out of scope.

Example

The following code shows an example of illegal deallocation of memory:
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char ** argv) { 
    char str[10] = ""; 
    ...
    printf("Str: %s\n",str); 
    ...
    free(str); 
    return 0; 
}