Memcpy () resulting in EXC_BAD_ACCESS on iOS

I am getting NSData

in my function receive sockets and I am trying to copy this data into tempbuffer

my audio class, for this I am using a global variable of external type.

This is my code:

memcpy([recorder tempBuffer].mdata,(__bridger const void *)data,data.length);

      

Here the recorder is my extern

audio class type global variable .

When the control reaches this line of code, an exception is thrown, possibly an error.

+3


source to share


2 answers


There are three possibilities here:

  • [recorder tempBuffer].mdata

    is not a valid pointer. (What type is it, for example? If it is NSMutableData, you should be able to access the property mutableBytes

    .)
  • [recorder tempBuffer].mdata

    is not a valid enough pointer ( data.length

    ).
  • (__bridger const void *)data

    is not a valid pointer of sufficient size.


Of the three, I can guarantee that problem # 3 needs to be addressed. NSData is not the data itself, but the object you need. Instead of using a bridge here, you should use data.bytes

.

The other two, I cannot help you. I don't know what type mdata

is there or where it was allocated.

+5


source


If the destination buffer is indeed a buffer allocated with an malloc

or uint8_t

(or equivalent) buffer, you must:

  • Make sure the destination buffer is large enough to hold all the content data

    .

  • Don't try to use a pointer NSData

    for (void *)

    , but use:

    memcpy(destination, data.bytes, data.length);
    
          

    If NSData

    not in a contiguous block (which may not be the same in iOS 7 and later), data.bytes

    copy it to an adjacent buffer, which you can then use with memcpy

    .

  • Or better, you can avoid this redundant copy by deleting memcpy

    altogether:

    [data getBytes:destination length:data.length];
    
          

    This will, if NSData

    not in a contiguous block, don't let it be data.bytes

    copied to an adjacent buffer, which you then copied with memcpy

    .

    The bottom line NSData

    has a rich interface that should eliminate the need for low-level calls memcpy

    .



From the question, it is not clear what is [recorder tempBuffer].mdata

and how you isolated it, so maybe you can clarify. Hopefully this is not another object NSData

you are trying to copy.

0


source







All Articles