简体   繁体   中英

Heap error in for loop using const type variable?

For just practice, using QT library I am trying to select a folder and list the name of the dicom files in that folder. The following is code for that:

int main(int argc, char* argv[])
{


    QApplication app(argc, argv);
    QString fileName = QFileDialog::getExistingDirectory();


    if (fileName.isEmpty())
    {
        std::cout << "Got an empty file!\n";
    }
    else
    {
        QStringList nameFilter;
        QDir dir(fileName);
        nameFilter << "*.dcm";
        QFileInfoList list = dir.entryInfoList( nameFilter, QDir::Files );
        int numberOfFiles=list.count();

        for(int i=0;i<numberOfFiles;i++)
        {
            QString filena=list[i].fileName();
            string a=filena.toStdString();
            cout<<a<<endl;

        }
    }
   return 0;
}

Here I have found out that the function toStdString , which is actually std::string QString::toStdString () const , gives Heap error. I know the replacement to get rid of this error is to use toLocal8Bit().constData() , but I'm curious what's the main reason behind the heap error provided by toStdString. Is it because it is const type and my for loop is trying overwrite the const variable everytime?

Your code looks good - make sure your Qt's dll files are compiled with the same compiler (and with same Debug/Release configuration) you are using.

To answer some of your questions:

Is it because it is const type and my for loop is trying overwrite the const variable everytime?

No, your for loop is not trying to overwrite const variable. Const variable is on the right side of the assingment operator, so your for loop is reading from const variable, and it doesn't overwritting anything (your a variable is local variable visible inside for loop's block, so a is different in each pass of the loop).

Even if you try to overwrite const variable, that would not compile - trying to change const will break in compile-time, and not in runtime.

  1. This code works for me.
  2. You'd better not convert strings to std::string and use std::cout , but rather use QTextStream for output:

     QTextStream out(stdout); //... QString filena=list[i].fileName(); out << filena << endl; 

My money would be on mixing Debug versions of the Qt Framework with Release versions of your compiled program.

Especially under Windows a different heap manager is used in debug and release builds.

Try recompiling in debug mode and seeing what happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM