Problems with pointers are among the most difficult encountered by C programmers. Insure++ detects 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 second attempt at the “Hello world” program that uses dynamic memory allocation.

/*
 * File: hello2.c
 */
#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);
}

In this program, 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 to the new size. Notice that the code is careful to include the final NULL character when computing the string length (line 17) and also the space between strings (line 22). Both of these are easy mistakes to make. It’s an interesting exercise to see how quickly Insure++ finds such an error.

The code in lines 23-28 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 29 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 23 and 24. This is because the variable string_so_far hasn’t been set to anything before the first trip through the argument loop.

  • No labels