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.
source to share
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 propertymutableBytes
.) -
[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.
source to share
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 withmemcpy
. -
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 bedata.bytes
copied to an adjacent buffer, which you then copied withmemcpy
.The bottom line
NSData
has a rich interface that should eliminate the need for low-level callsmemcpy
.
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.
source to share