Problems with Open-Source Downloads read and

Problem with deleting pointer

  • i have a class with :
    @QLCDNumber *lcd;@

    in some function addLCD() i'm declaring it:
    @ lcd = new QLCDNumber(this);
    lcd->setGeometry(5, 43, 75, 30);
    in other function hideLCD() i'm hiding it:
    @ if(lcd->isVisible())
    // delete lcd; // that doesn't work!
    in third function begin() i'm using these functions in that way:
    hideLCD(); // here i wanna clear memory
    The problem is with deleting pointer! When i'm using this , it shows me segmentation fault. Without comment in hideLCD() it's working fine.
    bq. Debugger throws me an error:
    Program received signal SIGSEGV, Segmentation fault.
    0x08055c48 in QWidget::testAttribute (this=0x81eac38,
    attribute=Qt::WA_WState_Visible) at /usr/include/qt4/QtGui/qwidget.h:1025
    1025 return data->widget_attributes & (1<<attribute);
    Why is he doing that?

  • You created it like this:
    @lcd = new QLCDNumber(this);@
    so this (instance of your class) is the parent of lcd, so that will delete it when it is deleted (out of scope or deleted by you or deleted by parent if if has one)

    If you delete it yourself and then Qt parent-child mechanisms try to delete it again you can get seg-fault errors.

  • you can delete widgets from a parent child relationship and the relations will be fixed by deleting the widget, that works.

    But are you sure, your widget is created before you call hideLCD()? is it a valid pointer to a valid widget?
    Do you set something like destroy on close flags etc?

  • Am i sure? I'm ensuring that by:
    in constructor.
    If it is a valid pointer to a valid widget? Well, If I can hide it so I think it's valid.
    Destroy on close flags? Where can i set that?

    I'm using that lcd on slot (slot is calling only by clicking some button).
    I'm setting
    and those two functions.

    And for understanding: if I would like to clean up this pointer, i have to call it in destructor of my class, right?

  • Hi,

    first of all:

    if ifBegun a bool or an int? if it's a bool initialise it by ifBegun=false and set ifBegun=true inmstead of 1, otherwise don't compare it to false.

    second, the pointer you use is lcd.

    To make it safer, you could use QPointer<QLCDNumber>, which sets itself to 0 if the object is destroyed and which is always 0 as initial state.

    If you always want to destroy the object when you hide it, you can delete it directly, no need of first hiding it. To make it a bit safer, call lcd->deleteLater() which will delete the object in the next event loop run.

  • I suspect the lcd to be destroyed whilst it is still needed by Qt internals. A complete stack trace should give us more insight. deleteLater() should be safe too, as Gerolf mentioned.

    On the other hand: why delete and recreate the lcd? Shouldn't calling hide() be enough?

Log in to reply