whenever i run this code:

void _freecommands(void)
{
	command_t *com;

	for(com = cmd.commands; com->name; com = com->next)
		free (com);
}

i get one, even though i've malloc'd them previously and the conditional statement checks if they're not valid

i don't understand why, can someone help me?

Recommended Answers

All 2 Replies

command_t's are in a linked list btw, and cmd.commands is the start of that list

Break it down into a while loop and the problem stands out more.

com = cmd.commands;

while (com->name) {
    free(com);
    com = com->next;
}

The code frees com and then immediately uses the freed pointer to reset itself. Freed pointers are off limits, all you are allowed to do is assign to them. Instead, there is a pattern for freeing a linked list with a temporary pointer to the next node.

command_t *temp;

for (com = cmd.commands; com->name; com = temp) {
    temp = com->next;
    free(com);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.