Forgetting to Allocate Memory for a String

If you declare a string as a pointer, don't forget to allocate memory for it. This example tries to create a char pointer named ptr and initialize it with a string:

main()

{

char *ptr;

strcpy( ptr, "Ashby" ); /* Error! */

}

The pointer declaration char *ptr; creates a pointer variable but nothing else. It allocates enough memory for the pointer to store an address but doesn't allocate any memory to store the object to which ptr will point. The strcpy operation in the next line overwrites memory by copying the string into an area not used by the program.

One way to allocate memory is by declaring a char array large enough to hold the string:

main()

{

char c_array[10];

strcpy( c_array, "Randleman" );

}

You can also call the malloc library function to allocate memory at run time:

#define BUFFER_SIZE 30

#include <malloc.h>

main()

{

char *ptr;

if( ptr = (char *) malloc( BUFFER_SIZE ) )

{

strcpy( ptr, "Duvall" );

printf( ptr );

free( ptr );

}

}