Search code examples
objective-ccmemcpy

memcpy leads to EXC_BAD_ACCESS


I'm converting someone else's C++ to (Objective) C, but I'm having a problem with memcpy. I use it as follows:

memcpy((void *)virtualFlash[virtualFlashAddress], data, dataLength);

The variables are defined as follows:

unsigned char virtualFlash[5 * 1024 * 1024]; // 5MB
NSUInteger virtualFlashAddress; // set to 8 later on
unsigned char *data = (unsigned char *)[recordData bytes]; // recordData is an NSData object
NSUInteger dataLength = [recordData length]; // same NSData object

I get an EXC_BAD_ACCESS on the line of the memcpy. I debugged recordData, which returned <d8ffbd27 2000b1af 1c00b0af 2400bfaf>, and dataLength, which returned 16--both correct.

memcpy((void*)virtualFlash[8], data, 16);

This crashes. I've read that memmove works sometimes, but not in my case (same EXC_BAD_ACCESS). I'm unsure what to do, as this is almost exactly copied from the C++ program in which it works fine. My knowledge of C is very minimal, so I may be missing something obvious.


Solution

  • unsigned char virtualFlash[5 * 1024 * 1024]; // 5MB
    

    Your stack may or may not be large enough to accomodate a 5MB allocation. Even if it is, that's really pushing it a bit and I would allocate that amount dynamically. Next problem:

    (void *)virtualFlash[virtualFlashAddress]
    

    virtualFlash[virtualFlashAddress] returns a char, unlikely to be a valid address. Seems like you meant to write:

    virtualFlash + virtualFlashAddress
    

    Where virtualFlashAddress is an offset applied to the base address virtualFlash (i.e., the address of the first element in the array).

    The name virtualFlashAddress is confusing as it is being used as an index into that array, but that's my best guess without seeing more code.