Tóth Attila Tóth Attila - 3 months ago 19
C Question

My implementation of strcpy not working properly

I've just written my strcpy function but it doesn't work properly. After x amount of characters I have an infinite loop or it will copy my string but give me an error...

char *ft_strcpy(char *dest, char *src)
{
int i;

i = 0;
while (*(src + i) != '\0')
{
*(dest + i) = *(src + i);
i++;
}
*(dest + i) = NULL;
return (dest);
}

Answer

In this example :

 char a[] = "abc";
 char b[] = "xyzsadasdasdadsi";

You're trying to put 17 characters into string char *a, which is supposed to store only 4 of them.

You can not do this. You must use a new string in which you allocated enough memory to store the characters needed, using strlen(), for example :

char *new = malloc(sizeof(char) * (strlen(src) + 1));

Plus, you should also correct your function :

char    *ft_strcpy(char *dest, char *src)
{
   int i;

   i = 0;
   while (*(src + i) != '\0')
   {
        *(dest + i) = *(src + i);
        i++;
   }
   *(dest + i) = '\0';
   return (dest);
}