Tóth Attila
Tóth Attila

Reputation: 149

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);
}

Upvotes: 1

Views: 377

Answers (2)

souki
souki

Reputation: 1385

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);
}

Upvotes: 3

Oolira
Oolira

Reputation: 1

Maybe you should allocate memory manually with malloc and terminate the string with '\0' (not NULL which is different).

Like

dest = (char *)malloc(sizeof(char) * strlen(src) + 1));
dest[strlen(src)] = '\0';

Upvotes: 0

Related Questions