Qt World Summit: Submit your Presentation

QList and segmentation fault

  • Hi, i'm trying to run a piece of code, which contains something like this:
    int count(){
    int n=nodes.count();
    return n;
    QList<Node*> nodes;
    On Win 7 this works perfectly, but on Ubuntu 11.04 crashes most of times with segmentation fault error (still sometimes it works). I figured out that something is wrong with the QList and calling count() is the exact place of the crash. Do you have any ideas?

    P.S. What is really weird - the object is NOT even constructed yet when the crush occurs. It is not a surprise, that callin a method causes a crash but how is it possible?

  • Can you provide us a complete, compilable small test case, please? The code looks ok so far.

  • Well i found a workaround but I still have some questions. sorry for being such a noob)

    So I have this object, called a structure (the above code is a piece of its class declaration) and a widget, that uses the structure to draw some diagram in reimplemented paintEvent. The thing is, when application starts, the structure pointer is not defined. So I just wrote
    if (!structure ) return;
    for this case. But still (sometimes) even structure has not been constructed yet, still it was NOT null and the code after that was executed. So, it appears that is not a valid check for whether an object was constructed or not, doesn't it?

    P.S. Yes, and the workaround was simply to create the dummy object for structure, actually it makes perfect sense anyway

  • In that case you must set the structure pointer to null (0) early. At least before you use it somewhere. The initial value of a pointer is not guaranteed to be null, it may contain garbage (depending on the compiler) and you most probably stepped into that trap.

  • thank you very much, the simple thing that pointers are like other variables and should always be initialized just slipped off my mind

  • It hits me too, from time to time - no need to worry :-)

Log in to reply