Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy behaving differently on ios7

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?

like image 751
Mariano Latorre Avatar asked Mar 28 '26 21:03

Mariano Latorre


1 Answers

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.

like image 70
verbose Avatar answered Apr 02 '26 22:04

verbose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!