Project

General

Profile

WTimer causes segfault when accessing destructed class variables

Added by Zach Motsinger over 8 years ago

I have encountered this issue multiple times, and it's always difficult for me to track down, so I thought I'd see if anyone else has any similar issues.

Basically, I set up a timer to call a function that modifies a member variables of my widget class. Then, before the timer finishes and executes the function, the user navigates away from the page and causes destruction of the widget class. However, the timer still appears to be running, and will eventually execute the code in the function it is pointing at. This, in turn, causes a segfault because the function is modifying class variables that no longer exist.

Specifically, this is what I see:

void MyClass::Foo()
{
    Wt::WTimer::singleShot(1000, this, &MyClass::Bar);
}

void MyClass::Bar()
{
    classBool = false;
}

Here, MyClass will call Foo() just before the user navigates away from the page and causes destruction of MyClass. However, Bar() will still be executed and will encounter a segfault when modifying the value of classBool.

Is this intended behavior? I have tried making the timer a member variable and explicitly checking and stopping it in the destructor, but I still seem to have the issue. So far, removing the timer and refactoring the code is the only solution I have found. Which leads me to wonder what the intended use is for timers when page contents are so dynamic.

Any help or suggestions would be greatly appreciated. Thanks!


Replies (3)

RE: WTimer causes segfault when accessing destructed class variables - Added by Trigve Siver over 8 years ago

I think that timer events are sent from the client (browser) and on the server it executes only the given functor.

I think that it is your responsibility to track the lifetime of the objects used in timer callbacks.

The one solution is to run the timer callback "one level up", that is in class that has direct control of your MyClass instance, to find out if the timer callback should be processed or not.

RE: WTimer causes segfault when accessing destructed class variables - Added by Koen Deforche over 8 years ago

Hey,

Wt will automatically disconnect signal/slots (which is underlying the singleShot() implementation) when the target object of the slot is being destroyed, but only if that target object is a WObject. I guess your 'MyClass' does not specialize WObject?

Regards,

koen

RE: WTimer causes segfault when accessing destructed class variables - Added by Trigve Siver over 8 years ago

Good to know! I was under the impression that only signal/slot processing does respect "trackable" objects.

    (1-3/3)