-3

When I compile this code I experience a bus error and I don't understand what I'm doing to cause this. I read up what a bus error entails and I still don't quite see my problem. This code should reproduce the behaviour of the strcpy() function in the string.h library.

#include <unistd.h>

void ft_putstr(char *str)
{
 while (*str)
  write(1, str++, 1);
}

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

 index = 0;
 while (src[index] != '\0')
 {
  dest[index] = src[index];
  index++;
 }
 dest[index] = '\0';
 return (dest);
}

int main(void)
{
 char *str1, *str2, *cpy;

 str1 = "Cameron";
 str2 = "Why you no work?";
 cpy = ft_strcpy(str1, str2);
 ft_putstr(cpy);
 return (0);
}
Cameron Shirley
  • 127
  • 1
  • 1
  • 8

1 Answers1

1
char *name = "string";

creates a string literal in the memory, that can't be later rewritten. Use malloc and your function instead of this initialization like this.