Hey guys,
Objective C has spoiled me, especially with ARC, so I need to double check something on C memory management. Take the following example:
I'm assuming that the second call to doStuffWithStruct(0) will cause aStruct.spriteData to leak. I'm wondering about two possible solutions.
Solution 1
Solution 2
So, which, if either, of these will prevent a memory leak? Also, do I need to go through and free the memory for all of the myStruct objects in myStructArray before terminating the application, or will that be taken care of for me when the array itself is freed?
Objective C has spoiled me, especially with ARC, so I need to double check something on C memory management. Take the following example:
Code:
typedef struct myStruct {
u8 * spriteData;
} myStruct;
myStruct myStructArray[16];
void doStuffWithStruct(int i) {
myStruct aStruct = myStructArray[i];
u8 * data = malloc(1024);
doStuffWithData(data);
aStruct.spriteData = data;
}
int main() {
doStuffWithStruct(0);
doStuffWithStruct(0);
}
I'm assuming that the second call to doStuffWithStruct(0) will cause aStruct.spriteData to leak. I'm wondering about two possible solutions.
Solution 1
Code:
typedef struct myStruct {
u8 * spriteData;
} myStruct;
myStruct myStructArray[16];
void doStuffWithStruct(int i) {
myStruct aStruct = myStructArray[i];
u8 * data = malloc(1024);
doStuffWithData(data);
aStruct.spriteData = data;
/*
Free data here. This is like retaining properties in Obj-C,
but I'm concerned aStruct.spriteData will then point to
NULL or garbage in this instance
*/
free(data);
}
int main() {
doStuffWithStruct(0);
doStuffWithStruct(0);
}
Solution 2
Code:
typedef struct myStruct {
u8 * spriteData;
} myStruct;
myStruct myStructArray[16];
void doStuffWithStruct(int i) {
myStruct aStruct = myStructArray[i];
/*
Free data here if it already exists. Is the if statement needed
to prevent attempting to free NULL if aStruct.spriteData has
not yet been allocated, or is freeing a NULL pointer ok?
*/
if (aStruct.spriteData) {
free(aStruct.spriteData);
}
u8 * data = malloc(1024);
doStuffWithData(data);
aStruct.spriteData = data;
}
int main() {
doStuffWithStruct(0);
doStuffWithStruct(0);
}
So, which, if either, of these will prevent a memory leak? Also, do I need to go through and free the memory for all of the myStruct objects in myStructArray before terminating the application, or will that be taken care of for me when the array itself is freed?
Last edited by mashers,