Reputation: 11
I have a game I am working on that uses a linked list for the entities in the game. I have found what I think to be some sort of bug. Note, I'm coding in C. But after this trouble with C pointers I'm thinking about trying C++ techniques.
In my debug testing two projectiles were colliding which blows both of them up. Basically the situation is this:
Starting in Entity's move function: 1) Projectile entity moves 2) Loop through all entities checking collision at this new location 3) If collision, in this case between projectiles, remove both
I pass a double pointer of the entity to the function that does collision. That entity may be removed but I still need to use it for advancing the entity to the next one in the list (in the while loop). If that didn't make sense it is seen as this:
ENTITY *node;
while (node)
{
...
entity_do_collision (&node); // <-- node may be removed in this function
//Debug
if (node == global_node)
{
}
else
node = global_node;
node = node->next; // <-- pass a double pointer above so this works here
}
So, I've ran through the code so many times and don't see any illegal operations. The part that gets me is sometimes the double pointer will work and sometimes it won't. I tested using a global entity pointer (that always works) to compare back in my entity move function to test if the node being removed matches what it was set to in the entity remove function.
This description is a little abstract, so let me know if I need to explain more.
Upvotes: 0
Views: 99
Reputation: 4513
Original code:
ENTITY *node;
while (node)
{
...
entity_do_collision (&node); // <-- node may be removed in this function
node = node->next;
/* the function can have changed node's value
** but on the next iteration ( on the **value** of node->next)
** the original node->next will not be affected!
*/
}
Sample code using pointer tot pointer:
ENTITY **pp;
for (pp = &global_node; *pp; pp = &(*pp)->next)
{
...
entity_do_collision (pp); // <-- *pp (= node) may be removed in this function
...
}
Upvotes: 0
Reputation: 13003
There are zillion solutions which would or would not work for your exact problem.
Here are some ideas to start with:
etc.
Sidenote: You should never use linked lists in 21th's century (an era of hierarchies of caches, prefetching, out-of-order execution and mutithreading), unless you really, really have no other choice and you understand what you are doing. Use arrays by default, swith to something else only if you find it reasonable.
More info:
Upvotes: 2