Program crash when trying to retrieve an U32 from a struct

82 views Asked by At

I have been asked to finish some code someone else started, and I am completely confused on how to copy a U32 value inside an struct. These are the relevant parts of the various structs; note that I am trimming a lot because those are some seriously huge structs:

typedef struct AttackerList {
    U32 count;
} AttackerList;

typedef struct AggroVars {
    AttackerList attackerList;
}

typedef struct Player {
    U32 aiAttackers;
}

Now, in the function I am trying to modify:

void attackTarget(Player* target) {
   AggroVars* aiTarget;
   // Tons of code here.
   aiTarget->attackerList.count++;
   target->aiAttackers = aiTarget->attackerList.count;
   // Tons more code here.
}

That last line is the one that is causing me all sorts of grief. It does work, I can see in the debug output how many critters are attacking the player; but it causes a crash whenever the AI loses interest in the target. I know this has something to do with pointers, but sprinkling asterisks on the code results in either "invalid indirection" or "differs in levels of indirection". I am pretty much stumped on how to retrieve just the value of aiTarget->attackerList.count without any weird pointer stuff.

2

There are 2 answers

1
Jens On

Instead of "sprinkling asterisks" I suggest sprinkling assertions in the tons of code we don't see after these variables were initialized or modified:

#include <assert.h>

...
assert (target != NULL);
assert (aiTarget != NULL);

This might point you in the right direction.

2
Jayesh Bhoi On

you need first to allocate memory for each structure so in your code make below changes

void attackTarget(Player* target) 
{
   AggroVars* aiTarget = malloc(sizeof(AggroVars));

   aiTarget->attackerList.count++;

   target->aiAttackers = aiTarget->attackerList.count;

}