Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Program compiles but generates a segmentation fault.



  • Hello all,

    First time here. Sorry if this is not the right forum to post questions.
    New to C++ and Qt5, but I have programmed GUI interfaces using Python (Tkinter, PyGtk, PyQt).

    My program uses the Qt5 gui library with C++. It compiles fine and shows no errors but terminates with a segmentation fault.

    /* file : hbsplitter.cpp */
    #include <QHBoxLayout>
    #include <QSplitter>
    #include <QString>
    
    #include "hbsplitter.h"
    
    #include "mlabelwidget.h"
    #include "mtextedit.h"
    
    Hbsplitter::Hbsplitter(QWidget *parent) : QWidget(parent)
    {
      QHBoxLayout *hbox = new QHBoxLayout(this);
      QSplitter *splitter1 = new QSplitter(Qt::Horizontal);
      Mtextedit *myMtextedit = new Mtextedit();
      Mlabelwidget *myMlabelwidget = new Mlabelwidget();
      QString newLabel;
      newLabel = "Qt with cpp.";
      myMlabelwidget->show();
      myMlabelwidget->changeText(newLabel);
      /* if I uncomment the above line I get "zsh: segmentation fault  ./stage3"
       * where stage3 is the name of the executable */
      splitter1->addWidget(myMtextedit);
      splitter1->addWidget(myMlabelwidget);
      hbox->addWidget(splitter1);
    }
    

    The Mlabelwidget files :

    /* file : mlabelwidget.h */
    
    #pragma once
    
    #include <QWidget>
    #include <QLabel>
    
    class Mlabelwidget : public QWidget
    {
      public:
        Mlabelwidget(QWidget *parent = 0);
        QLabel *label;
        void changeText(QString input);
    };
    
    /* file : mlabelwidget.cpp */
    
    #include <QWidget>
    #include <QHBoxLayout>
    #include <QLabel>
    #include <iostream>
    #include "mlabelwidget.h"
    
    Mlabelwidget::Mlabelwidget(QWidget *parent) : QWidget(parent)
    {
      QHBoxLayout *hbox = new QHBoxLayout(this);
      QLabel *label = new QLabel();
      label->setText("This is Qt");
      hbox->addWidget(label);
    }
    
    void Mlabelwidget::changeText(QString input) {
      std::cout << "Mlabelwidget::changeText() called." << "\n";
      /* std::cout << input << "\n"; */
      label->setText(input); 
      std::cout << "Mlabelwidget::changeText() completed." << "\n";
    }
    

    Here's a gist with the rest of the files.

    Using Debian Linux, gcc, Makefile(generated by running qmake).

    Instead of using

    void changeText(QString input);

    I have tried using a string as argument to the settext function for the label.

    My programming experience with GUI is limited to Python with (Tkinter or PyGtk). I have tried to model the experience with Tkinter(Python Tk Module) to Qt5(with C++). I assumed it would work, it compiles fine but produces a segmentation fault.

    I have identified the line which when commented out prevents a segmentation fault and shows a working GUI window.

    Thank you in advance!


  • Lifetime Qt Champion

    @zlinux20 said in Program compiles but generates a segmentation fault.:

    QLabel *label = new QLabel();

    This will not initialize the member variable.



  • @zlinux20 said in Program compiles but generates a segmentation fault.:

    public:
    Mlabelwidget(QWidget *parent = 0);
    QLabel *label;
    void changeText(QString input);

    A coding style suggestion:

    QLabel *m_label;
    

    Naming all member variables with an m_ prefix tells you that you are using a member variable. This helps distinguish between temporary/stack variables and the member variables in your class. Its a nice mental reminder.


  • Qt Champions 2017

    @fcarney said in Program compiles but generates a segmentation fault.:

    Naming all member variables with an m_ prefix tells you that you are using a member variable. This helps distinguish between temporary/stack variables and the member variables in your class.

    Although Qt uses that style I don't agree. Firstly, hungarian notation is very ugly, and verbose, and was never proven to be anything but actual noise. I'd rather see descriptive (possibly long) names that speak to me than to struggle with half-standard type/semantic prefixes.
    And secondly, a good IDE is going to draw you a picture (quite literally using different colors) for the different types of variables. Default color scheme for creator makes members orange-brown, while locals are dark blue and globals are black. Sorry, but no prefix, no matter how long, is going to give you more information than color-coding. If you don't trust me take a resistor and ponder a bit why they give the value in color bands; it's ultimately practical!



  • @kshegunov

    Well, other than long identifiers...they suck

    and I have yet to find an IDE that works the way I develop code and that doesn't crash 30 minutes into using it.


  • Qt Champions 2017

    @Kent-Dorfman said in Program compiles but generates a segmentation fault.:

    @kshegunov

    Well, other than long identifiers...they suck

    Long's a relative term and context is everything. Although I don't like abrreviating I'm known to do it on occasion. I'd always prefer HermitePolynomial, to HermPoly though. The other extreme is to go the way they did it in that crappy old language - fortran - where identifiers had unreasonable length limits, so zpotrf is supposedly doing a "Cholesky factorization of a complex Hermitian positive definite matrix A"[1], but no sane person could deduce that by name.

    and I have yet to find an IDE that works the way I develop code and that doesn't crash 30 minutes into using it.

    Well I write in C++ and it's strongly typed (more or less), so unless I hate myself and use auto (the dreaded compiler-inferred typing) all over, I know exactly what types I'm dealing with instantly. And Creator, which is far from perfect mind you, can provide tooltips if I suddenly and inexplicably had forgotten. It haven't crashed on me for a long time too. I don't know what's the status with python, though, so I can't comment on that.



  • @kshegunov said in Program compiles but generates a segmentation fault.:

    rather see descriptive (possibly long) names that speak to me

    Definitely +1 on this point. With copy/paste and auto complete this really has no excuse not to use long variable names. It definitely makes thing more understandable.

    The m_ prefix helps me understand things a bit quicker with or without the color coding. The part I like the most is functions that take variables that are intended to be set to a member.

    void memberFunction(int index){
        m_index = index;
    }
    

    That way I can use the same variable name and show intent both ways.


  • Qt Champions 2017

    @fcarney said in Program compiles but generates a segmentation fault.:

    That way I can use the same variable name and show intent both ways.

    You can be even more explicit without the prefix:

    void SomeClass::someMember(int index)
    {
        this->index = index;
    }
    


  • This post is deleted!

  • Lifetime Qt Champion

    @Kent-Dorfman I don't think @kshegunov was talking about loop variables like i or j.
    "one line comments inserted throughout to explain what the thing does" - everywhere where the variable is used?
    It is highly subjective but I prefer variable/class names which are self-descriptive over short names.


  • Qt Champions 2017

    @Kent-Dorfman, @jsulm

    Indeed. As usual it's compromise between utility and brevity. I, personally, rarely have variables that are over the 12 chars too, but I'm much more lenient when it comes to the types or methods involved. Yes, it makes sense not to go too long on the variables, especially the locals, but when you call something out of the current scope it does help if you can tell what it does, hence my mention of the zpotrf, which really tells you nothing about what this does. If it were called choleskyHermitian, or if it were encapsulated in a proper type (i.e. a template or something) it'd make much more sense than just:

    MyMatrixTypedef x = zpotrf(y, ....);
    

    Example (excerpt from a test case):

    HermiteQuadrature integral(maxOrder);
    for (Hermite<real>::Order n = 1; n <= maxOrder; n++)  {
        Hermite<lreal> Hnm1(n - 1), Hn(n);
        xHermite xHn(n);
    
        real lhs = std::sqrt(2 * lreal(n)) * integral.evaluate(Hnm1);
        real rhs = integral.evaluate(xHn);
        if (isEven(n))
            QVERIFY(isEqual(lhs, rhs));        // Integrating an odd function gives zero
        else  {
            // ...
        }
    }
    

    You should be able to tell at a glance what this does, which is the point of a good style. If you can't then my style isn't good.



  • @Christian-Ehrlicher

    I ended up using this

    label = new QLabel("default label");
    label->setText("This is Qt");
    

    to get it to work. I also realize that I might need to learn a lot more about C++ classes and pointers before translating my Python gui code to C++ gui code.

    Thank you.



  • @zlinux20
    Are you saying you have written these two lines literally one after the other? What is the point of initializing the label with one string if you are going to change it to a different string immediately thereafter?



  • @JonB

    Initially I had this

    // mlabelwidget.cpp snippet
    QLabel *label = new QLabel();
    label->setText("This is Qt");
    QWidget::update();
    
    and this in my class declaration
    //mlabelwidget.h snippet
    class Mlabelwidget : public QWidget
    {
      public:
        Mlabelwidget(QWidget *parent = 0);
        QLabel *label;
        void changeText(QString input);
    };
    

    when I found the hint of removing "QLabel *" from the declaration at this link I removed the "QLabel *" part and it worked i.e. there were no more segmentation faults. I wanted to report my progress and posted those lines that you mention. I left the second line in there from my earlier experiments, trying to initialize the QLabel. It is not needed now and my code is working as intended.

    p.s. I am familiar with GUI Programming with Python Tkinter etc. I am learning just enough C++ at the moment to create a GUI program that needs to be an exe file as opposed to a Python script (client requirement).



  • FWIW, something else that seems conspicuously missing is that I'm not seeing the Q_OBJECT macro defined in your class definitions that inherit from QObject.

    That macro is required so that the MOC system understands that the class is subject to Qt framework meta-processing. Just a wag, but revert to the original version and add the Q_OBJECT macro in the header file like follows:

    MyClass: public QWidget {
    
    Q_OBJECT
    .
    .
    .
    }
    


  • @Kent-Dorfman

    Thank you for the hint. I did see it in some examples and noted it for future reference. I forgot all about it by the time I was working through (working/tutorial) examples I found online. I will be using the Q_OBJECT to change my existing (toy) program(s) to see how it works out.


Log in to reply