Threads and pointers

Hi,

In my code originally I did

1
2
3
4
5
    if (player[playerID] != 0)
    {
        delete player[playerID];
        player[playerID] = 0;
    }


This caused my program to crash because my game uses multi-threading so I changed the code to

1
2
3
4
5
6
7
    if (player[playerID] != 0)
    {
        Player* p;
        p = player[playerID];
        player[playerID] = 0;
        delete p;
    }



And now it works fine because I null the pointer before freeing the memory. But to me this looks a bit ugly, is it a bit hacky doing it like that if so do you know any alternatives?

I am also a bit worried because lets say in my code it goes something like this

1
2
3
4
if (PlayerHandler::player[i] != 0)
{
   PlayerHandler::player[i]->process();
}


and then after it checks if the pointer is null my other thread frees the memory and nulls the pointer. It is too late then process is called! is this a possibility?

Maybe I should flag players for deletion? and then in the program outside of the thread delete it their?
Last edited on
Have you considered using smart pointers (for example, std::shared_ptr)? These will automatically delete the pointer upon the destruction of the last pointer to it, or you can call reset to delete the pointer and set it to null. I am also fairly certain that they are thread safe, and from memory if the stored pointer is a null pointer then derefencing it with the -> operator simply doesn't do anything.
No I have never tried them how would I make a smart pointer?
Last edited on
First you need to decide which one you want to use.
http://www.cplusplus.com/reference/memory/
Topic archived. No new replies allowed.