简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM