ioscobjective-cmemcpymemory-corruption

How iOS handles memory corruption from low level C/ Objective-C code?


I have an iOS app that uses some legacy low level memory manipulation code using pointers. I'm debugging an issue where multiple threads are causing multiple copies of these code to be executed on global variables simultaneously and cause memory corruption by writing invalid length or overwriting data.

The effect is that the length of the buffer below may change. I've seen iOS throw EXC_BAD_ACCESS or EXC_BREAKPOINT as a result of these calls.

My question is - would iOS always throw exceptions when I use memcpy incorrectly, or will it complain only when I write outside my allowed memory?

In other words, is my code free to corrupt my memory and create invisible issues, without causing exceptions, as long as it does not step outside allocated memory or access deallocated memory?

NSData* buffer = ...
Byte *array = (Byte*)malloc(buffer.length);
memcpy(array, buffer.bytes, buffer.length);

Solution

  • The last time I checked or had such an issue it would only complain when outside your own allowed memory. In my situation I was writing over whatever objects followed the address I was trying to write to. The result was what seemed a random crash on objects as unrelated as even NSString.

    My mistake was something like the following:

    MyStructure *myStructure = malloc(sizeof(myStructure)); // Incorrect
    MyStructure *myStructure = malloc(sizeof(MyStructure)); // Fixed
    

    A simple autocomplete error which led to days long hunting of this bug. MyStructure was a fairly big one so accessing some property (both read and write) would in this case simply overflow and read/write through whatever was after it. It eventually randomly crash; sometimes bad access, other times just some random exception on a random object.