Search code examples
c++qtqwidgetqtguiqlayout

A simple qt program not running with error message saying "segmentation fault"


It was successful to compile it but when I run it, the terminal gave me a "Segmentation fault (core dumped)" message. The compiler I use is g++ on Ubuntu.

The code is:

#include <QApplication>
#include <QLabel>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QWidget>

int main(int argc, char** argv){
  QApplication app(argc, argv);

  QWidget window;
  QLabel *label = new QLabel;
  QLineEdit *edit = new QLineEdit;
  QObject::connect(edit, SIGNAL(textChanged(const QString&)), label, SLOT(setText(const QString&)));

  QVBoxLayout *layout;
  layout->addWidget(edit);
  layout->addWidget(label);
  window.setLayout(layout);

  window.show();


  return app.exec();
}

Solution

  • QVBoxLayout *layout is not initialized, you're using an uninitialized pointer.

    Correct way:

    QVBoxLayout *layout = new QVBoxLayout;
    // use layout..
    

    http://qt-project.org/doc/qt-4.8/qvboxlayout.html