我在尝试运行 QProcess
时遇到了一个非常奇怪的问题在类里面HmiApplication
,源自 QApplication
.
应用程序在 main.cpp
的第 6 行抛出一个 SIGSEGV .这仅在 hmiapplication.cpp
的第 11 行发生被注释掉了(如果我不 qDebug()
QProcess 的标准输出)。
为了简单明了,我在创建 QProcess 时没有处理任何返回值。
主要.cpp
#include "hmiapplication.h"
int main(int argc, char **argv)
{
HmiApplication hmi(argc, argv);
return hmi.exec(); // LINE 6 - SIGSEGV
}
hmi应用.h
#ifndef HMIAPPLICATION_H
#define HMIAPPLICATION_H
#include <QApplication>
#include <QProcess>
class HmiApplication : public QApplication
{
Q_OBJECT
public:
HmiApplication(int argc, char **argv);
virtual ~HmiApplication();
private:
QProcess *macFinder = nullptr;
};
#endif // HMIAPPLICATION_H
hmi应用程序.cpp
#include "hmiapplication.h"
HmiApplication::HmiApplication(int argc, char **argv) : QApplication(argc, argv)
{
macFinder = new QProcess(this);
macFinder->start("arping", QStringList() << "-c 2" << "192.168.1.1");
macFinder->waitForReadyRead();
QString ret(macFinder->readAllStandardOutput());
ret = ret.mid(ret.indexOf('[') + 1, 17);
qDebug() << ret; // LINE 11
}
HmiApplication::~HmiApplication()
{
}
编辑:
如果我添加 QVector<Camera*> cameras;
到标题和
for(quint8 i = 0; i < 10; i++) {
Camera *cam = new Camera(i);
cameras.append(cam);
}
到源文件,我是否删除qDebug()
并不重要行,并且在这两种情况下都会抛出段错误。
Camera
是 QLabel
的派生类并且在没有 QProcess
的情况下也能完美工作上面提到过。
最佳答案
QApplication
constructor通过引用接受它的第一个参数...
QApplication::QApplication(int &argc, char **argv)
文档还警告...
The data referred to by argc and argv must stay valid for the entire lifetime of the QApplication object. In addition, argc must be greater than zero and argv must contain at least one valid character string.
但是,您将argc
按值 传递给HmiApplication
。因此,QApplication
构造函数接收到对本地拷贝的非常量引用,该拷贝将在 HmiApplication
构造函数的末尾超出范围,导致稍后出现未定义的行为。
将构造函数的签名更改为...
HmiApplication::HmiApplication(int &argc, char **argv)
关于c++ - exec() 中的 Qt 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47330449/