问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/18826047/strcpy-behaving-differently-on-ios7