Finding Dynamic Memory Errors with Memory Error Detection Tools

Posted on Jul 12, 2012

Using dynamically allocated memory properly is a tricky issue. In many cases, programs continue to run well after a programming error causes serious memory corruption; sometimes they don’t crash at all.

A common mistake is trying to reuse a pointer after it has already been released. Consider lines 22-26 in the following program that de-allocates memory blocks before allocating the larger ones:

 dangling pointer

1:  /*

2:   * File: hello4.c

3:   */

4:  #include <stdlib.h>

5:  #include <string.h>


7:  main(argc, argv)

8:    int argc;

9:    char *argv[];

10:   {

11:   char *string, *string_so_far;

12:   int i, length;


14:   length = 0;


16:   for(i=0; i<argc; i++) {

17:         length += strlen(argv[i])+1;

18:         string = malloc(length+1);

19:  /*

20:   * Copy the string built so far.

21:   */

22:  if(string_so_far != (char *)0) {

23:  free(string_so_far);

24:  strcpy(string, string_so_far);

25:           }

26:           else *string = '\0';


28:         strcat(string, argv[i]);

29:         if(i < argc-1) strcat(string, " ");

30:         string_so_far = string;

31:   }

32:   printf("You entered: %s\n", string_so_far);

33:   return (0);


Dangling Pointers

If you run this code through memory error detection tool such as  Parasoft Insure++, you’ll get an error message about a “dangling pointer” at line 23. A dangling pointer is one that no longer points to a valid memory block. In this case, the block is freed at line 22 and then used in the next line. This is another common problem that often goes unnoticed because many machines and compilers allow this particular behavior.


What Other Dynamic Memory Problems Can Memory Error Detection Tools Find?

In addition to this type of dangling pointer dynamic memory problem, memory error detection tool such as  Parasoft Insure++also detect 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 with NULL or uninitialized pointers.
  • Passing nonsensical arguments or arguments of the wrong data type to malloc, calloc, realloc or free.



Image credit: xithorian

If you’d like more information on how Parasoft's Insure++ can help you find memory errors, check out our Insure++ eKit or visit the Parasoft Insure++ page.