Exagon Exagon - 3 months ago 7
C++ Question

Passing stack allocated objects by pointer to a function which executes on another thread

As far as I know threads sharing heap memory but have their own stack.
So if I pass a stack allocated object via pointer (for polymorphic reasons) to a function which is executed on another thread, will this be safe, or will I get undefined behaviour. For example this code:

struct Foo{
int counter{0};
}

void bar(Foo * obj){
obj->counter++;
}
int main(){
{
Foo foo_object;
std::thread t(bar, &foo_object);
t.detach();
}
//do more stuff
}


Is this unsafe, because after
foo_object
goes out of scope, the pointer to
foo_object
will be invalid, but the thread could access the invalid memory?
I have a strong feeling, this is produces undefined behaviour, but I am not 100% sure.

Answer

No this is not safe. Once you get to the } in

{
    Foo foo_object();
    std::thread t(bar, &foo_object);
    t.detach();
}

foo_object will go out of scope and you will be left with a dangling pointer in the detached thread. Since we do not know when the thread will actually start it is entirely plausible that the stack based local object will already be destroyed when you go to use it.


Also note that Foo foo_object(); is a function declaration and not a local variable. To have a variable you need Foo foo_object;.