G'Day,
Just a quick query on memory management.
I have a dynamic array of a particular struct.
Code:
struct myStruct
int stuff;
...
void * anotherStruct;
}
As the code suggests the field anotherStruct can point to a number of different structs. Each of these structs may contain zero or more pointers to allocated memory. Rather than having a complex cleanup routine I though this might be a better way.
Code:
struct allocatedMemory {
//array of pointers
void ** memPtrs[];
int numElements;
}
struct diffStruct1 {
struct allocatedMemory am;
char * ptr1;
unsigned char * ptr2;
}
and more diffStructs something like above.
Then, whenever I fill out one of the diffStructs I also fill out the allocatedMemory struct contained within it with an array of all the pointers to allocated memory in the diffStruct.
Code:
ds.am.memPtrs = malloc(2 * sizeof(void *) );
ds.am.memPtrs[0] = ds.ptr1;
ds.am.memPtrs[1] = ds.ptr2;
ds.am.numElements = 2;
Then when it comes time to cleanup it is as easy as:
Code:
//loop through array of my structs
struct allocatedMemory *t = (myStruct[index]).anotherStruct
for (int x = 0;x< t->numElements;t++) {
free(t->memPtrs[x])
}
Does anyone have comments on this approach? Is it portable? Is there other ways?