Stefan B Stefan B - 1 year ago 137
C++ Question

C++ Stack around variable is corrupted

I am trying to implement a timer, which takes a function pointer as a parameter and a time in milliseconds. After the time is passed, the function should be called in a separate thread. The code looks as follows:

class timer
{
public:
void schedule(void(*function)(), int time)
{
std::thread t = std::thread([&]
{
std::this_thread::sleep_for(std::chrono::milliseconds(time));
function();
});
t.detach();
}
};


The main method looks as follows:

#define LOG(x) std::cout << x << std::endl;


timer t1;
timer t2;
timer t3;
t1.schedule([] {LOG("t1 done")}, 2000);
t2.schedule([] {LOG("t2 done")}, 3000);
t3.schedule([] {LOG("t3 done")}, 4000);
std::this_thread::sleep_for(std::chrono::seconds(20));


The exception is as follows:

Run-Time Check Failure #2 - Stack around the variable 't1' was corrupted.

Answer Source

The issue here is you are capturing by reference in your lambda. This means that it is possible for you to call detach and exit from schedule before the operator() of the lambda is called. If that happens then when you try to use time you are accessing a dangling reference.

The solution here is to capture by value instead. This means you get a copy and it doesn't matter when the operator() is called as the lambda doesn't rely on anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download