Exception at 0x7fff0ce8e878, code: 0xc0000005: read access violation at: 0xffffffffffffffff, flags=0x0 (first chance)

331
10 сентября 2018, 19:50

У меня стала возникать ошибка : Exception at 0x7fff0ce8e878, code: 0xc0000005: read access violation at: 0xffffffffffffffff, flags=0x0 (first chance)

qwidget.cpp 1133

Причём она возникает только в релизной компиляции(Выпуск), в отладочной (отладка) исключения не возникает.

Не могу понять почему так, когда запуская отладку в релизной компиляции. Выбрасывает на строке : Таким образом я вообще не понимаю из-за какой строчки кода выбрасывает.

Сам код очень большой, весь даже не опубликовать:

 #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainTab = new QTabWidget(this);
    VBLMain = new QVBoxLayout(this);
    HBLDisk = new QHBoxLayout(this);
    WidgetLog = new QWidget(this);
    HBLLog = new QHBoxLayout(this);
    QVBoxLayout *HBLLog_one = new QVBoxLayout(this);
    QGroupBox *groupBoxLog = new QGroupBox(tr("Обязательное поле. Добавление можно начать, только с выбора журнала."));
    groupBoxLog->setLayout(HBLLog);
    HBLLog_one->addWidget(groupBoxLog);
    Login conn;
    conn.connOpen();
    QSqlQuery *query = new QSqlQuery(conn.mydb);
    QSqlQuery *ComboBoxQueryColor = new QSqlQuery(conn.mydb);
    if (ComboBoxQueryColor->exec("SELECT \"Цвет\" FROM \"SchemeObservationLog\".settingslog WHERE id = 1 ")) {
        while (ComboBoxQueryColor->next()) {
           BoolColorCheckBox = ComboBoxQueryColor->value(0).toBool();
        }
    } else {
        QMessageBox::warning(this, tr("Ошибка базы данных"),ComboBoxQueryColor->lastError().text());
    }
    if (query->exec("SELECT * FROM \"SchemeObservationLog\".log")) {
        int ItemComBox = 0;
        while (query->next()) {
            ComboBoxLog->addItem(query->value(1).toString(), QVariant(query->value(0).toInt()));
            if (BoolColorCheckBox == true) {
                ComboBoxLog->setItemData( ItemComBox, QColor( query->value(3).toString()), Qt::BackgroundRole );
            }
            ItemComBox++;
        }
        ComboBoxLog->setCurrentIndex(-1);
    }else{
        QMessageBox::warning(this, tr("Ошибка базы данных"),query->lastError().text());
    }
    conn.connClose();
    connect(ComboBoxLog, SIGNAL(currentIndexChanged(int)),this, SLOT(ComboBoxLogChange()));
    HBLLog->addWidget(ComboBoxLog);
    //NewLogButton = new QPushButton("Создать новый журнал",this);
    //connect(NewLogButton, SIGNAL(clicked(bool)), this, SLOT(NewLogDialog()));
    //HBLLog->addWidget(NewLogButton);
    MainWindow::FormLogBuilding();
    HBLLog_one->addWidget(SpoilerFormLog);
    WidgetLog->setLayout(HBLLog_one);
    ui->verticalLayout_Log_Filters->addWidget(WidgetLog);

    helpDisk = new QLabel("Выберите кнопку 'Автоматическое определение файлов на устройстве' или Файл>Получить с устройства");
    WidgetVDisk = new QWidget(this);
    VBLMain->addWidget(helpDisk);
    WidgetVDisk->setLayout(VBLMain);
    DownloadFilesButton = new QPushButton("Автоматическое определение файлов на устройстве",this);
    connect(DownloadFilesButton, SIGNAL(clicked(bool)), this, SLOT(ListFiles()));
    HBLDisk->addWidget(DownloadFilesButton);
    WidgetDisk = new QWidget(this);
    WidgetDisk->setLayout(HBLDisk);
    VBLMain->addWidget(WidgetDisk);
    TableDisk = new QTableView(this);
    VBLMain->addWidget(TableDisk);
    SaveFilesButton = new QPushButton("СОХРАНИТЬ",this);
    connect(SaveFilesButton, SIGNAL(clicked(bool)), this, SLOT(SaveFiles()));
    VBLMain->addWidget(SaveFilesButton);
    Progress = new QProgressBar(this);
    VBLMain->addWidget(Progress);
    Progress->hide();
    MainTab->addTab(WidgetVDisk,"Файлы в выбранном устройстве");  

    QVBoxLayout *LogMainBoxLayout = new QVBoxLayout();
    Spoiler* spoilerLog = new Spoiler("Выбрать фильтер",900,LogWidget);
    auto *LogSpoilerLayout = new QGridLayout();
    LogMainBoxLayout->addWidget(spoilerLog);
    MainWindow::TableLogBuilding("SELECT * FROM \"SchemeObservationLog\".data");
    Login connComboBox;
    connComboBox.connOpen();
    QSqlQuery *queryComboBox = new QSqlQuery(connComboBox.mydb);
    if (queryComboBox->exec("SELECT * FROM \"SchemeObservationLog\".log")) {
        int ItemComBox = 0;
        while (queryComboBox->next()) {
            ComboBoxLogFilter->addItem(queryComboBox->value(1).toString(), QVariant(queryComboBox->value(0).toInt()));
            if (BoolColorCheckBox == true) {
                ComboBoxLogFilter->setItemData( ItemComBox, QColor( queryComboBox->value(3).toString()), Qt::BackgroundRole );
            }
            ItemComBox++;
        }
        ComboBoxLogFilter->setCurrentIndex(-1);
    } else {
        QMessageBox::warning(this, tr("Ошибка базы данных"),queryComboBox->lastError().text());
    }
    if (queryComboBox->exec("SELECT * FROM \"SchemeObservationLog\".devices")) {
        while (queryComboBox->next()) {
            if (!queryComboBox->value(2).isNull()) {
                ComboBoxDeviceFilter->addItem(queryComboBox->value(2).toString(), QVariant(queryComboBox->value(0).toInt()));
            } else {
                ComboBoxDeviceFilter->addItem(queryComboBox->value(5).toString(), QVariant(queryComboBox->value(0).toInt()));
            }
        }
        ComboBoxDeviceFilter->setCurrentIndex(-1);
    }else{
        QMessageBox::warning(this, tr("Ошибка базы данных"),queryComboBox->lastError().text());
    }
    connComboBox.connClose();
    QLabel *LabelLogFilter = new QLabel(tr("Фильтер по журналам."));
    QLabel *LabelDeviceFilter = new QLabel(tr("Фильтер по устройствам."));
    QPushButton *FilterButton = new QPushButton(tr("Фильтр"));
    connect(FilterButton,SIGNAL(clicked(bool)),this, SLOT(FilterTableLog()));
    LogSpoilerLayout->addWidget(LabelLogFilter,0,0);
    LogSpoilerLayout->addWidget(LabelDeviceFilter,0,1);
    LogSpoilerLayout->addWidget(ComboBoxLogFilter,1,0);
    LogSpoilerLayout->addWidget(ComboBoxDeviceFilter,1,1);
    LogSpoilerLayout->addWidget(FilterButton,1,2);
    LogMainBoxLayout->addWidget(TableLog);
    LogWidget->setLayout(LogMainBoxLayout);
    spoilerLog->setContentLayout(*LogSpoilerLayout);
    MainTab->addTab(LogWidget,"Данные визуального контроля");
    MainWindow::TableAnalysisBuilding("SELECT * FROM \"SchemeObservationLog\".analysis");
    MainWindow::FormAnalysisBuilding();
    MainTab->addTab(WidgetAnalysis,"Лабораторный контроль");
    ui->verticalLayout_Main->addWidget(MainTab);
}
MainWindow::~MainWindow()
{
    delete ui;
}
void  MainWindow::FormLogBuilding() {
    if (!ComboBoxLog->currentData().isNull()) {
        Login conn;
        conn.connOpen();
        QSqlQuery* FormLogSelectQuery = new QSqlQuery(conn.mydb);
        if(FormLogSelectQuery->exec("SELECT  \"Название\", \"Комментарий\","
                                    " \"Температура_воздуха(°C)\",\"Температура_воды(°C)\","
                                    " \"Скорость_ветра(м/с)\", \"Скорость_течения(м/с)\","
                                    "\"Направление_ветра(0°-360°)\", \"Направление_течения(0°-360°)\","
                                    "\"Время_начала_операции\", \"Время_окончания_операции\", \"Путь_до_журнала\""
                                    " FROM \"SchemeObservationLog\".log  WHERE id ="+ComboBoxLog->currentData().toString())) {
            while (FormLogSelectQuery->next()) {
                for (int i = 0; i < FormLogListLineEdit.size(); ++i) {
                    FormLogListLineEdit[i]->setText(FormLogSelectQuery->value(FormLogListLineEdit[i]->objectName().toInt()).toString());
                }
                for (int i = 0; i < FormLogListTextEdit.size(); ++i) {
                    FormLogListTextEdit[i]->setText(FormLogSelectQuery->value(FormLogListTextEdit[i]->objectName().toInt()).toString());
                }
                for (int i = 0; i < FormLogListLabelMS.size(); ++i) {
                    FormLogListLabelMS[i]->setText(FormLogSelectQuery->value(FormLogListLabelMS[i]->objectName().toInt()).toString());
                }
                LogPushButtonFolder->setEnabled(true);
                LogFolder = FormLogSelectQuery->value(LogPushButtonFolder->objectName().toInt()).toString();
            }
        } else {
            QMessageBox::warning(this, tr("Ошибка базы данных"),FormLogSelectQuery->lastError().text());
        }
        conn.connClose();
    } else {
        Login conn;
        conn.connOpen();
        QSqlQuery* FormLogSelectQuery = new QSqlQuery(conn.mydb);
        if (FormLogSelectQuery->exec("SELECT \"Название\", \"Комментарий\","
                                     " \"Температура_воздуха(°C)\",\"Температура_воды(°C)\","
                                     " \"Скорость_ветра(м/с)\", \"Скорость_течения(м/с)\","
                                     "\"Направление_ветра(0°-360°)\", \"Направление_течения(0°-360°)\","
                                     "\"Время_начала_операции\", \"Время_окончания_операции\",\"Путь_до_журнала\""
                                     " FROM \"SchemeObservationLog\".log ")) {
            QSqlRecord recordTable = FormLogSelectQuery->record();
            int count = recordTable.count();
            int row = 0;
            int rowTime = 0;
            QGroupBox *MeteorologicalSituation = new QGroupBox("Метеорологическая обстановка");
            QGroupBox *TimeGroupBox = new QGroupBox("Время");
            QGridLayout *GridLayoutMS = new QGridLayout;
            QGridLayout *GridLayoutTime = new QGridLayout;
            for (int n=0; n<count; n++) {
                QSqlField fieldTable = recordTable.field(n);
                if (fieldTable.type() == QVariant::String && recordTable.fieldName(n) != "Комментарий" && recordTable.fieldName(n) != "Путь_до_журнала") {
                    QLabel *FormLogLabel = new QLabel(recordTable.fieldName(n));
                    //FormLogLabel->setText(recordTable.fieldName(n));
                    FormLogSpoilerLayout->addWidget(FormLogLabel,n,0);
                    QLineEdit *FormLogLineEdit  = new QLineEdit(this);
                    FormLogLineEdit->setEnabled(false);
                    FormLogLineEdit->setText("Выберите журнал!");
                    FormLogLineEdit->setObjectName(QString("%1").arg(n));
                    FormLogSpoilerLayout ->addWidget(FormLogLineEdit,n,1);
                    FormLogListLineEdit.push_back(FormLogLineEdit);
                    //row++;
                } else if (fieldTable.type() == QVariant::String && recordTable.fieldName(n) == "Комментарий") {
                    QLabel *FormLogLabel = new QLabel(recordTable.fieldName(n));
                    //FormLogLabel->setText(recordTable.fieldName(n));
                    FormLogSpoilerLayout->addWidget(FormLogLabel,n,0);
                    QTextEdit *FormLogCommentTextEdit = new QTextEdit (this);
                    FormLogCommentTextEdit->setEnabled(false);
                    FormLogCommentTextEdit->setText("Выберите журнал!");
                    FormLogCommentTextEdit->setObjectName(QString("%1").arg(n));
                    FormLogSpoilerLayout->addWidget(FormLogCommentTextEdit,n,1);
                    FormLogListTextEdit.push_back(FormLogCommentTextEdit);
                    //row = row + 5;
                } else if (fieldTable.type() == QVariant::Double) {
                    QLabel *FormLogLabel = new QLabel(recordTable.fieldName(n));
                    GridLayoutMS->addWidget(FormLogLabel,row,0);
                    QLabel *FormLogLabelMS = new QLabel(this);
                    FormLogLabelMS->setObjectName(QString("%1").arg(n));
                    GridLayoutMS->addWidget(FormLogLabelMS,row,1);
                    FormLogListLabelMS.push_back(FormLogLabelMS);
                    row++;
                } else if (fieldTable.type() == QVariant::Int) {
                    QLabel *FormLogLabel = new QLabel(recordTable.fieldName(n));
                    GridLayoutMS->addWidget(FormLogLabel,row,0);
                    QLabel *FormLogLabelMS = new QLabel(this);
                    FormLogLabelMS->setObjectName(QString("%1").arg(n));
                    GridLayoutMS->addWidget(FormLogLabelMS,row,1);
                    FormLogListLabelMS.push_back(FormLogLabelMS);
                    row++;
                } else if (fieldTable.type() == QVariant::DateTime) {
                    QLabel *FormLogLabel = new QLabel(recordTable.fieldName(n));
                    GridLayoutTime->addWidget(FormLogLabel,rowTime,0);
                    QLabel *FormLogLabelTime = new QLabel(this);
                    FormLogLabelTime->setObjectName(QString("%1").arg(n));
                    GridLayoutTime->addWidget(FormLogLabelTime,rowTime,1);
                    FormLogListLabelMS.push_back(FormLogLabelTime);
                    rowTime++;
                } else if (fieldTable.type() == QVariant::String && recordTable.fieldName(n) == "Путь_до_журнала") {
                    LogPushButtonFolder->setObjectName(QString("%1").arg(n));
                    connect(LogPushButtonFolder,SIGNAL(clicked(bool)),this, SLOT(OpenFolder()));
                }
            }
            LogPushButtonFolder->setEnabled(false);
            TimeGroupBox->setLayout(GridLayoutTime);
            FormLogSpoilerLayout->addWidget(TimeGroupBox,0,3,2,1);
            MeteorologicalSituation->setLayout(GridLayoutMS);
            FormLogSpoilerLayout->addWidget(MeteorologicalSituation,0,4,2,2);
            FormLogSpoilerLayout->addWidget(LogPushButtonFolder,3,0,1,6);
        } else {
            QMessageBox::warning(this, tr("Ошибка базы данных"),FormLogSelectQuery->lastError().text());
        }
        conn.connClose();
        SpoilerFormLog->setContentLayout(*FormLogSpoilerLayout);
    }
}
void MainWindow::ComboBoxLogChange () {
    MainWindow::FormLogBuilding();
    MainWindow::TableLogBuilding("SELECT * FROM \"SchemeObservationLog\".data  WHERE id_log ="+ComboBoxLog->currentData().toString());
    MainWindow::TableAnalysisBuilding("SELECT * FROM \"SchemeObservationLog\".analysis WHERE id_log ="+ComboBoxLog->currentData().toString());
}
void MainWindow::OpenFolder() {
    if (!LogFolder.isEmpty()) {
        QString file_name = QDir::cleanPath(LogFolder);
        QDesktopServices::openUrl(QUrl(QUrl::fromLocalFile(file_name)));
    } else {
        msgBox.setText("Что то пошло не так. Папка не создалась.\n");
        msgBox.exec();
    }
}
void MainWindow::SaveFiles()
{
    if (!ComboBoxLog->currentData().isNull()) {
        SaveFilesButton->setDisabled(true);
        Progress->show();
        Progress->setMinimum(0);
        Progress->setMaximum(model->rowCount()-1);
        Login conn;
        conn.connOpen();
        QSqlQuery* queryAddNote = new QSqlQuery(conn.mydb);
        QString newDir = "";
        for (int i=1;i<model->rowCount();i++) {
            newDir = QString(QDir::currentPath()+"/"+ComboBoxLog->currentText()+"_%1"+"/"+model->index(i,2).data().toString()).arg(QString(QDate::currentDate().toString()).replace(" ","_"));
            if (QDir(newDir).exists() == false) {
                QDir().mkpath(newDir);
            }
            if (model->index(i,0).data(Qt::DisplayRole).toBool()==true) {
                QString FileType = MainWindow::getFileType(QFileInfo(model->index(i,1).data().toString()).fileName());
                qDebug()<<FileType;
                if (FileType == "Рисунок JPEG") {
                    QString pathFile = model->index(i,1).data().toString();
                    QByteArray pathFileBA = pathFile.toLocal8Bit();
                    const char *pathFileChar = pathFileBA.data();
                    // Read the JPEG file into a buffer
                    FILE *fp = fopen(pathFileChar, "rb");
                    if (!fp) {
                        msgBox.setText("Не удается открыть файл.\n");
                        msgBox.exec();
                        qDebug()<<"Не удается открыть файл.\n"<<pathFileChar;
                    }
                    fseek(fp, 0, SEEK_END);
                    unsigned long fsize = ftell(fp);
                    rewind(fp);
                    unsigned char *buf = new unsigned char[fsize];
                    if (fread(buf, 1, fsize, fp) != fsize) {
                        msgBox.setText("Не удается прочитать файл.\n");
                        msgBox.exec();
                        delete[] buf;
                    }
                    fclose(fp);
                    // Parse EXIF
                    easyexif::EXIFInfo result;
                    int code = result.parseFrom(buf, fsize);
                    delete[] buf;
                    if (code) {
                        msgBox.setText(QString("Ошибка анализа EXIF: код %1 \n").arg(code));
                        msgBox.exec();
                    }
                    ThreadsCopy* threadA = new ThreadsCopy("thread A",model->index(i,1).data().toString(),newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName());
                    threadA->start();
                    QString sqlQueryAddNote = QString("INSERT INTO \"SchemeObservationLog\".data (data,path_to_data,id_log,latitude,longitude,date_create,id_devices) VALUES ('%1','%2','%3','%4','%5','%6','%7')")
                            .arg(QFileInfo(model->index(i,1).data().toString()).fileName())
                            .arg(newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName())
                            .arg(ComboBoxLog->currentData().toString())
                            .arg(QString::number(result.GeoLocation.Latitude))
                            .arg(QString::number(result.GeoLocation.Longitude))
                            .arg(result.DateTimeOriginal.c_str())
                            .arg(model->index(i,4).data().toString());
                    queryAddNote->prepare(sqlQueryAddNote);
                    queryAddNote->exec();
                } else if (FileType == "Файл \"GPX\"") {
                    ThreadsCopy* threadB = new ThreadsCopy("thread B",model->index(i,1).data().toString(),newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName());
                    threadB->start();
                    QFile file(model->index(i,1).data().toString());
                    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                        qDebug() << "File open error:" << file.errorString();
                        return;
                    }
                    QXmlStreamReader inputStream(&file);
                    while (!inputStream.atEnd() && !inputStream.hasError())
                    {
                        inputStream.readNext();
                        if (inputStream.isStartElement()) {
                            QString name = inputStream.name().toString();
                            if (name == "wpt")
                                qDebug() << "lon:" << inputStream.attributes().value("lon") << "lat:" << inputStream.attributes().value("lat");
                            if (name == "name")
                                qDebug() << "name:" << inputStream.readElementText();
                            if (name == "time")
                                qDebug() << "time:" << inputStream.readElementText();
                        }
                    }
                } else {
                    ThreadsCopy* threadC = new ThreadsCopy("thread C",model->index(i,1).data().toString(),newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName());
                    threadC->start();
/*                  QMediaPlayer *player = new QMediaPlayer(this);
                    player->setMedia(QUrl::fromLocalFile(model->index(i,1).data().toString()));
                    connect(player, SIGNAL(metaDataChanged()), SLOT(metadata_capture()));
                    QString GPSLatitudeVideo = "";
                    QString GPSLongitudeVideo = "";
                    QDateTime DateTimeOriginalVideo;
                    qDebug()<<model->index(i,1).data().toString()<<"+++";

                    if (player->isMetaDataAvailable())
                    {
                      GPSLatitudeVideo = player->metaData(QMediaMetaData::GPSLatitude).toString();
                      GPSLongitudeVideo = player->metaData(QMediaMetaData::GPSLongitude).toString();
                      DateTimeOriginalVideo = player->metaData(QMediaMetaData::Date).toDateTime();
                      qDebug()<<"+++"<<GPSLatitudeVideo<<GPSLongitudeVideo<<DateTimeOriginalVideo;
                    }
*/
                    QString sqlQueryAddNote = QString("INSERT INTO \"SchemeObservationLog\".data (data,path_to_data,id_log,id_devices) VALUES ('%1','%2','%3','%4')")
                            .arg(QFileInfo(model->index(i,1).data().toString()).fileName())
                            .arg(newDir+"/"+QFileInfo(model->index(i,1).data().toString()).fileName())
                            .arg(ComboBoxLog->currentData().toString())
                            //.arg(GPSLatitudeVideo)
                            //.arg(GPSLongitudeVideo)
                            //.arg(DateTimeOriginalVideo.toString())
                            .arg(model->index(i,4).data().toString());
                    queryAddNote->prepare(sqlQueryAddNote);
                    queryAddNote->exec();
                }
                Progress->setValue(i);
            } else {
            }
        }
        conn.connClose();
        Progress->hide();
        model->clear();
        SaveFilesButton->setDisabled(false);
        TableDisk->setModel(nullptr);        
        MainWindow::TableLogBuilding("SELECT * FROM \"SchemeObservationLog\".data");
        MainTab->setCurrentIndex(1);
    } else {
        msgBox.setText("Выберите журнал в ComboBox! Обязательное поле.");
        msgBox.exec();
        return;
    }
    return;
}
READ ALSO
Проблемы с созданием итератора

Проблемы с созданием итератора

Выполняю вот это заданиеНеобходимо написать итератор на лист векторов

221
бинарное дерево с негативными числами

бинарное дерево с негативными числами

Как написать код для binary tree с негативными числами ? Может есть примеры ?

213