I thought I understood this stuff, but I'm here at a standstill.
For a structure declared as:
typedef struct _Thing { uint32_t type; struct _Thing *children; unsigned long childCount; char *description; union { uint32_t thirtyTwoBitValue; char *nameValue; } data; } Thing;
I have a method that reassigns an array to host a new Thing object. It looks like this:
void AddTopLevelThing(Thing *thing) { Thing *oldThings = things; things = malloc(sizeof(Thing) * thingCount +1);
Note: things and thing The totality is global. Not a freak. ;-) Oh, and I also understand that this is a leak. One problem at a time ...
To create Thing objects, I created an initialization function. It looks like this:
Thing* CreateThingWithDescription(char *description) { Thing *thing = malloc(sizeof(Thing)); if (thing == NULL) { printf("Bad thing!, Bad!\n"); return NULL; }
To complicate the situation (not a pun), the Thing object has an array of children that are redistributed (grown) when new objects are added to it. It looks like this:
void AddChildThingToThing(Thing *parent, Thing *child) { Thing *oldChildren = parent->children; parent->children = malloc(sizeof(Thing) * parent->childCount + 1); if (parent->children == NULL) { printf("Couldn't allocate space for thing children.\n"); parent->children = oldChildren; return; }
In any case, it is difficult for me to determine why, when I finished creating my structures and adding child structures, they are often nullified, even if I confirmed their creation (in the debugger) when they were created. When the code in my main execution ends, I should have a tree structure, but instead itโs just a distorted mess of values โโthat I donโt recognize and donโt understand - thatโs why I think things are being rewritten.
In any case, I hope that I just miss something simple.
Here is my main one, if you want to see how I build a hierarchy of objects:
int main(int argc, const char * argv[]) { things = NULL; thingCount = 0; Thing *thing = CreateThingWithDescription("This is thing 1"); SetThingName(thing, "Willy Johnson"); AddTopLevelThing(thing); Thing *child = CreateThingWithDescription("This is child thing 1"); SetThingName(child, "Willy Son"); AddChildThingToThing(thing, child); child = CreateThingWithDescription("This is child thing 2"); SetThingName(child, "Willy Daughter"); AddChildThingToThing(thing, child); thing = CreateThingWithDescription("This is thing 2"); SetThingValue(thing, 700); AddTopLevelThing(thing); child = CreateThingWithDescription("This is child thing 3"); SetThingValue(child, 1024); AddChildThingToThing(thing, child); for (int i = 0; i < thingCount; ++i) { PrintThing(&things[i]); } return 0; }
Note: this is just a demo project to find out what is happening.