strcpy behaving differently on ios7

百般思念 提交于 2019-12-10 18:24:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!