C-array to NSData and back
I'm attempting to save a c-style array of Vertex3D structs to an NS开发者_Go百科Data object and get them back when reloading the app:
NSData *vert = [NSData dataWithBytes:&vertices length:(sizeof(Vertex3D) * NUM_OF_VERTICES)];
This data is then saved and attempted to be read back into my c-array thusly:
vertices = malloc(sizeof(Vertex3D) * NUM_OF_VERTICES);
[vert getBytes:&vertices length:(sizeof(Vertex3D) * NUM_OF_VERTICES)];
The above results in “EXC_BAD_ACCESS” followed by:
malloc: *** error for object 0x48423c0: pointer being freed was not allocated
I'm very new to programming so there's probably some fundamental memory management principle I'm unaware of. I have verified that the loaded NSData is identical to the saved one, but it's clear that the transition from c-array to NSData (and back) is not as I intended.
It's impossible to tell without seeing your declaration for the vertices
variable, but using &vertices
is probably wrong in the code you list in your question. If vertices
is a C array, then it is already a pointer and you should omit the address operator &
.
精彩评论