Puzzle S6

Copy characters from one string to another

[M-5]Write function that copies the characters contained in a source string to a target string. Copy the final null byte from the source string, as well. Assume that the target string has at least as many characters as the source string. The target string must already exist before the function is called, and any characters in it are over-written. Here is a prototype for the function:

void stringCopy( char *copy, char *source );

Here is a picture of what it does. The two strings are contained in buffers, which may have room for more characters than are logically contained in the null-terminated string. The buffers need not be the same size.

one string copied into a buffer

The two pointers move together through their respective strings until the source pointer hits the null at the end of its string. The function does nothing with the characters in the copy buffer that are left over from its original contents. Here is a testing program:

/* Puzzle S06 --  string copy */
#include <stdio.h>
#include <stdlib.h>

void stringCopy( char *copy, char *source )
{
}

int main()
{
  char buffer[100];
  char *trials[] = 
  {
  "The game is afoot!",
  "Genius is an infinite capacity for taking pains.",
  "So is programming.",
  "",
  "As always,\nlinefeeds should\nwork.",
  "Will\ttabs\t\tconfuse\tthings?",
  "For great fun, change the buffer size to 5!"
  };
  
  int j ;
  for ( j=0; j<sizeof(trials)/sizeof(char *); j++ )
  {
    stringCopy( buffer, trials[j] );
    printf("%s\n", buffer);
  }

  return 0;
}

This function is similar to the standard function strcpy() described in <strings.h> .

If you change the buffer size to 5, stringCopy() will not know it, and will blindly copy characters into the first 5 bytes of the buffer and beyond. This will likely clobber something else in memory. To see the effect of this, you may have to move the declaration of the buffer around in the code so that something crucial gets clobbered. Put it just before j, for example.

To somewhat allievate this problem, the standard function strncpy() described in <strings.h> requires an additional argument, the length of the buffer.



Previous Page        Answer         Next Page         Home