C Language

Finger Pointing

You can fall into another C pothole by forgetting that a pointer isn't the same as the thing it points to. The following code appears to save a copy of the current string in a "previous string" variable and then assign the current string a new value.

 char * curstr;
 char * prvstr;
 curstr = (char *) malloc( 10 );
 prvstr = (char *) malloc( 10 );
 strcpy( curstr, "abc" );
 prvstr = curstr;
 strcpy( curstr, "xyz" );

But after these statements are executed, both curstr and prvstr point to "xyz". The assignment prvstr = curstr copies the address stored in curstr to prvstr, not the contents of the memory location curstr points to.

Using *prvstr = *curstr won't accomplish what we want either. It just copies the single byte that curstr points to into the single byte that prvstr points to. To do a simple "save a copy of this string" operation, you require code like that in Figure 6.4. As is often the case in C, high-level operations that should be simple and safe are neither. I can offer only this caution: When working with pointers in assignment statements, double-check that you're using the right level of indirection. Most C compilers warn you about incompatible types or different levels of indirection in assignments, but they give no warning when both sides of an assignment are compatible types and levels but at the wrong level (as in the previous example).

Figure 6.4 Saving a Copy of a String

 prvstr = (char *) malloc( strlen( curstr ) + 1 );
 if ( prvstr == NULL ) {
    printf( "No memory available\n" );
 }
 else {
    strcpy( prvstr, curstr );
 }

by BrainBellupdated
Advertisement: