3

IOS7 seems to come with a new implementation (optimisation maybe) of strings strcpy. Before I was able to copy strings from any position of the array but now if I start copying from any position where (i % 4 != 0) it will crash.

To show this I ran this code both in iOS6 and 7, and it crashed the app on 7:

  char *x = malloc(1024);
  strcpy(x, "hello world");
  char *x2 = x + 1;
  strcpy(x, x2);

what am I doing wrong?

Mariano Latorre
  • 719
  • 1
  • 10
  • 21

1 Answers1

6

The C11 standard says at §7.24.2.3:

The strcpy function copies the string pointed to by s2 (including the terminating 
null character) into the array pointed to by s1. If copying takes place between 
objects that overlap, the behavior is undefined.

Undefined behavior means anything can happen--the code can work perfectly, it can crash, or it can work fine one day and crash the next. Since x and x2 overlap in your code, the fact that it worked in iOS 6 is just luck of the draw.

verbose
  • 7,827
  • 1
  • 25
  • 40
  • I'd consider the fact that it was running fine _bad_ luck, because it is a serious bug, and it wasn't found until a lot later. – gnasher729 Jun 03 '14 at 16:36