How to Find Pointer Abuse in C

Jun 7, 2012

Posted by Parasoft

Problems with pointers are among the most difficult encountered by C programmers. Memory error detection tools can detect pointer-related problems in the following categories:

  • Operations on NULL pointers.
  • Operations on uninitialized pointers.
  • Operations on pointers that don’t actually point to valid data.
  • Operations which try to compare or otherwise relate pointers that don’t point at the same data object.
  • Function calls through function pointers that don’t actually point to functions.

Below is the code for a “Hello world” program that uses dynamic memory allocation:

 

/*

 * File: hello2.c

 */

 Memory Error Detection

#include <stdlib.h>

#include <string.h>

main(argc, argv)

    int argc;

    char *argv[];

{

    char *string, *string_so_far;

    int i, length;

    length = 0;

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

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

        string = malloc(length+1);

 

/*

 * Copy the string built so far.

 */

 

        if(string_so_far != (char *)0)

            strcpy(string, string_so_far);

        else *string = '\0';

        strcat(string, argv[i]);

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

        string_so_far = string;

    }

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

    return (0);4

}

The basic idea of this program is that we keep track of the current string size in the variable length. As each new argument is processed, we add its length to the length variable and allocate a block of memory of the new size. Notice that the code is careful to include the final NULL character when computing the string length (line 11) and also the space between strings (line 14). Both of these are easy mistakes to make. It’s an interesting exercise to see how quickly you can find such an error with a memory error detection tool (here, we'll use Parasoft Insure++).

The code in lines 19-24 either copies the argument to the buffer or appends it, depending on whether or not this is the first pass round the loop. Finally, in line 25, we point at the new longer string by assigning the pointer string to the variable string_so_far.

If you compile and run this program under Insure++, you’ll see “uninitialized pointer” errors reported for lines 19 and 20. This is because the variable string_so_far hasn’t been set to anything before the first trip through the argument loop.

 

 

***

Photo Credit: oskay

You can learn more about Insure++ and uninitialized pointers at Parasoft's Memory Error Detection Resource Center.

New Call-to-action