0

I'm trying to understand this code below but Xcode is giving me an error at the 2nd to last line saying "Thread 1: signal SIGABRT"

char string1[4] = "abc";
char string2[4] = "def";

printf("%s \n%s\n", string1, string2);

strcpy(string1, string1+1); // Xcode points here, "Thread 1: signal SIGABRT"

printf("%s \n%s", string1, string2);

What's going on ? I expected it to print

abc
def
bc
def

but it obviously stops halfway through.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Arrow
  • 691
  • 2
  • 7
  • 15

1 Answers1

3

Quoted from strcpy documentation: The source and destination strings should not overlap, as the behavior is undefined.

Your source and destination overlap.

Use memmove() for overlapping data instead.

this
  • 5,229
  • 1
  • 22
  • 51
  • Isn't the fact that [this is modifying a literal string](http://stackoverflow.com/questions/5464183/modifying-string-literal) also important? – Jongware May 09 '14 at 21:33
  • 3
    It's not modifying a string literal. – Crowman May 09 '14 at 21:44
  • @PaulGriffiths: good thing I phrased it as a question then ;-) You are correct, as explained in the very link I pointed to. – Jongware May 09 '14 at 22:04