I want to save the state of my structs as a binary file and load them again. My structs look like this:
typedef struct
{
uint8_t pointerLength;
uint8_t *pointer;
uint8_t NumBla;
uinT16 Bla[MAX_NUM_Bla];
...
}
BAR_STRUCT, *BAR;
typedef struct
{
int numBar;
BAR bars[MAX_NUM_BAR];
}
FOO_STRUCT, *FOO;
Saving is no problem, but restoring the state. Iam at the point where the bytestring from the file is on the heap and a pointer is pointing to the first adress of this string. And I do as follows:
const void* dataPointer //points to adress in heap
unsigned char* bytePointer = (unsigned char*)dataPointer;
FOO foo = (FOO_STRUCT*)bytePointer;
bytePointer += sizeof(FOO_STRUCT);
for (int i=0; i < MAX_NUM_BAR; i++) {
foo->bars[i] = (BAR_STRUCT*)bytePointer;
}
The last assignment doesn't work and I get an EXC_BAD_ACCESS.
Because bars is an array of pointers i need to correct the adresses of each element is pointing to. Because they are not valid anymore. So I try to assign the adress of the object I saved in the bytesteam to foo->bars[i];
But I can not change foo->bars[i] at all. Accessing works but but assigning a new adress doesn't.
I wonder why.
Edit:
Iam working on OSX so to write bytes to file i use NSData:
bool saveCurrentState( FOO foo){
NSMutableData *data = [NSMutableData data];
[data appendBytes:templates length:sizeof(FOO_STRUCT)];
for (int i=0; i < MAX_NUM_BAR; i++){
[data appendBytes:&foo->bar[i] length:sizeof(INT_BAR_STRUCT)];
if( foo->bar[i] != NULL )
[data appendBytes:foo->bar[i]->pointer length:sizeof(uint8_t)*foo->bar[i]->length];
...
}
}
I can't really change the structs since they are used in a lib, which i don't really have access too. I am especially interested in why it is not working as expected. As you can see I copy the whole struct including the pointer itself and adding the structures the pointer were pointing to to the byte string. Hope this give a bit more clarification.
When reading byte stream to setup the structs i just need the change the values of the array with the new address and that for some reason doesn't want to work.
Edit: Iam also saving/reading the file with NSData:
NSData* data = [NSData dataWithContentsOfFile:@"path/to/file"];
const void* dataPointer = [data bytes];