Home > OS >  Why is pointer src (and c) being modified?
Why is pointer src (and c) being modified?

Time:08-24

For some reason the pointer src (and the array it points, c) gets modified when executing dest = ft_strcpy(dest, src) and printing it, giving some trash value at the beggining. However, if I just print the result of the function without doing the previous equalization, i.e, write(1, ft_strcpy(dest, src), 10), everything goes well. I know I can put directly c and c2, the error stays the same.

In short, doing dest = ft_strcpy(dest, src) if with the array pointed by dest (c2) is shorter than c 1, results in c getting modified.

char    *ft_strcpy(char *dest, char *src)
{
    char    *ptr1;
    char    *ptr2;

    ptr1 = src;
    ptr2 = dest;
    while (*src != '\0')
    {
        *dest = *src;
        src  ;
        dest  ;
    }
    *dest = '\0';
    src = ptr1;
    dest = ptr2;
    return (dest);
}


int main (void)
{
    char c[10] = "Hola Pepe ";
    char c2[10];
    char *src, *dest;
    src = c;
    dest = c2;

    write(1, src, 10);
    write(1, "\n", 1);
    write(1, dest, 10);
    write(1, "\n", 1);
    dest = ft_strcpy(dest, src);
    write(1, "----------\n", 11);
    write(1, src, 10);
    write(1, "\n", 1);
    write(1, dest, 10);
    //write(1, ft_strcpy(dest, src), 10);
}

CodePudding user response:

In main() your buffer c can hold up to 10 chars. But the string you assign to it is made up of 11 chars (including the NUL terminator \0).

So it should be declared as:

char c[11] = "Hola Pepe ";

Or if you want to leave the counting to the compiler:

char c[] = "Hola Pepe ";

You should also make sure your c2 buffer is big enough to hold whatever you want to copy into it:

char c2[11];

In the following code:

while (*src != '\0') {

       *dest = *src;
       src  ; 
       dest  ;
} 

*(dest   1)= '\0';

In the final iteration, the dest statement is executed which increments dest to where the \0 should be placed (at the end of the string).

In the line:

*(dest   1) = '\0';

You increment dest once more and then store \0 inside it. This is not what you want.

Instead you can just do the following and it will correctly terminate the string:

*dest = '\0';

  • Related