Memory leaks

Memory leaks occur if your program allocates memory and then does not free it and looses the references to that memory.


Memory leaks can generate the following runtime errors:
  • memory resource exhaustion
  • program termination

Detecting the error

The Memory Analysis tool detects this error if Perform leak check when process exits is checked and/or Perform leak check every (ms) is set to a nonzero value under Memory Errors in the configuration. In this case, memory leaks are trapped when the program exits normally (as opposed to aborting) and/or during a routine check at the preset regular time intervals.

Information returned by the Memory Problems view

The notification for this type of memory error includes the following details:
  • Severity: LEAK
  • Description: memory leak of size nbytes
  • Pointer: address of the lost pointer
  • Trap Function: always malloc
  • Alloc Kind: how memory was allocated for this block (malloc, calloc, or realloc)
  • Location: source file and line of code where the block was allocated (e.g., main.c:59)
  • Count: number of blocks leaked

How to fix memory leaks

Ensure that memory is deallocated on all paths, including error paths. If you enable Record memory allocation/deallocation events under Memory Errors, you can watch the results in the Memory Events view to find unmatched allocations where a corresponding free is needed to deallocate the memory.


The following code shows an example of a memory leak:
int main(int argc, char ** argv) {
  char * str = malloc(10);
  if (argc > 1) {
     str = malloc(20);
  printf("Str: %s\n",str);
  return 0;