I\'ve been trying to wrap my head around this the whole day...
Basically, I have a struct called State that has a name and another one called StateMachine with a name, a
It looks like you want to have a variable number of states in each state machine, but you are allocating the memory incorrectly. In create_state_machine
, this line:
temp->states = malloc(sizeof(struct State));
Allocates a single State
object, not an array of pointers (which is how you are using it).
There are two ways you could change this.
states
as State states[];
but then you cant ever have more than a fixed number of states.states
, so you can keep track of that as well as how much is used (which is what total_states
is being used for).The later would look something like this:
#include
#include
typedef struct
{
const char *name;
} State;
typedef struct
{
const char *name;
int total_states;
int states_capacity;
State *states;
} StateMachine;
StateMachine *create_state_machine(const char *name)
{
StateMachine *temp = malloc(sizeof(StateMachine));
memset(temp, 0, sizeof(*temp));
temp->name = name;
temp->states_capacity = 10;
temp->states = malloc(sizeof(State) * temp->states_capacity);
return temp;
}
State *add_state(StateMachine *machine, const char *name)
{
if (machine->total_states == machine->states_capacity)
{
// could grow in any fashion. here i double the size, could leave
// half the memory wasted though.
machine->states_capacity *= 2;
machine->states = realloc(
machine->states,
sizeof(State) * machine->states_capacity);
}
State *state = (machine->states + machine->total_states);
state->name = name;
machine->total_states++;
return state;
}