Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user's arguments are empty with QCoreApplication in mysterious cases

I'm trying to create a console application with Qt and been facing really strange behavior when attempting to retrieve the arguments. My class is derived from QCoreApplication which has a function that should normally put all the args in some list of strings. But in some cases that call ends in a segmentation fault.

Here's the code:

main.cpp

#include "Diagramm.h"

int main(int argc, char *argv[])
{
    Diagramm application(argc, argv);
    application.run();
    return EXIT_SUCCESS;
}

Diagramm.h

#include <QCoreApplication>
#include <iostream>
#include <QStringList>
#include <QFile>
#include <QDebug>


class Diagramm : public QCoreApplication
{
    Q_OBJECT

    public:
        Diagramm(int argc, char *argv[]);
        void run();
    private:
        void testArguments();
    signals:
    public slots:
};

Diagramm.cpp

#include "Diagramm.h"

Diagramm::Diagramm(int argc, char *argv[]) : QCoreApplication(argc, argv)
{
    //std::cout << "calling Diagramm constructor" << std::endl;
}

void Diagramm::run()
{
    testArguments();
}

void Diagramm::testArguments()
{
    //get source and target files from arguments
    QStringList arguments = this->arguments();

    if(arguments.count() < 2)
    {
        std::cout << "Missing arguments" << std::endl;
        return exit(1);
    }
}

When compiling and executing the code above, everything works fine, BUT when I uncomment the line in Diagramm's constructor I've got a segmentation fault on the first line of function testArguments (the call to arguments())

I've been on that for hours, reading Qt's doc, forums... Does anyone know where that can come from? Any idea would be greatly appreciated.

Note : I'm not calling the exec function on purpose because I don't need any event loop.

like image 519
Ote Avatar asked Aug 27 '12 02:08

Ote


1 Answers

Q(Core)Application wants argc and argv by reference, so your constructor should read

Diagramm(int& argc, char **argv[])

If you don't to this, it may work in some cases and lead to segfaults or strange behavior in others, as you encountered. Seems to be a common error and isn't easy to spot when reading the documentation.

like image 175
scai Avatar answered Nov 07 '22 10:11

scai