Alex
Alex

Reputation: 2299

Issue when implementing strcpy in C

For a homework assignment I'm supposed to implement all 22 functions of the string.h library (2fun2handle). I've gotten a lot of functions down, but am running into a bit of trouble when trying to implement strcpy.

After quite a few revisions, here is my attempt at the function:

char *new_strcpy(char *dest, const char *src){
    char *copy = (char *) src;
    for(; *copy != '\0'; ++copy, ++dest)
        *dest = *copy;
    return dest;
}

I thought this would work fine. However, when testing my code by doing a simple example like this:

char src[50], dest[50];
new_strcpy(src,  "src");
new_strcpy(dest,  "dest");
printf("dest: %s\n", dest);
printf("src: %s\n", src);

My output ends up looking like this:

dest: dest$
src: src$$$$

When it should just look like this:

dest: dest
src: src

Before implementing this function, I've copied src strings to dest strings by using pointers without issue.. so I'm not sure why this is happening now. Is there something obvious that I'm doing wrong? Also note that I've tried doing this with a while loop and looping until *copy is empty, and I've tried directly looping through the original *dest and *src arguments that get passed in.

Upvotes: 2

Views: 592

Answers (1)

Blindy
Blindy

Reputation: 67380

You never mark the actual string as finished, using the special zero character:

char *new_strcpy(char *dest, const char *src){
    char *copy = (char *) src;
    for(; *copy != '\0'; ++copy, ++dest)
        *dest = *copy;
    *dest=0;
    return dest;
}

Note that you don't need the copy variable, it's just garbage the compiler will remove for you.

Edit: as requested, the classic strcpy function that doesn't cast away const and is less verbose is as follows:

char *new_strcpy(char *dest, const char *src)
{
  char *ret = dest;            // needed to return, useless as this is
  while(*dest++ = *src++);     // straight byte copy, very unoptimized
  //*dest=0;                   // no longer needed since the copy happens before the check now
  return ret;                  // and return the original buffer (note that you were returning the end)
}

Upvotes: 5

Related Questions