简体   繁体   中英

Qt program seg faults when I try to insert a pair into a map

I am working on my first Qt application, widget really, and I am getting a segfault when I try to fill up a standard library map with a <int, QString> pair. My goal is to fill the map with int keys and QString values. I don't know if pair is the best way to do this, so any advice would be great.

Here is the only source file besides the main.

#include "linuxtips.h"
#include "ui_linuxtips.h"

LinuxTips::LinuxTips(QWidget *parent) :
  QWidget(parent),
  ui(new Ui::LinuxTips)
{
  loadRandTip();
  ui->setupUi(this);
}

LinuxTips::~LinuxTips()
{
  delete ui;
}

void LinuxTips::on_learnMore_clicked()
{

}

void LinuxTips::on_viewAll_clicked()
{

}

void LinuxTips::loadRandTip()
{
  int i = 0;
  std::map<int, QString>::iterator it;

  QString line;
  QFile inputFile(":/tipFile.txt");
  inputFile.open(QIODevice::ReadOnly);

  QTextStream in(&inputFile);
  do{
    line = in.readLine();
  //  this->TipMap.insert(it, std::pair<int, QString >(i,line));
    i++;
  }while(!in.atEnd());
}

If I uncomment this->TipMap.insert(it, std::pair<int, QString >(i,line)); then it will run. Since it's a seg fault I'm sure its a memory overflow or null pointer, but I'm just not sure what it is. Thanks for any help.

I'm going to assume that your crash is due to these lines:

std::map<int, QString>::iterator it;
this->TipMap.insert(it, std::pair<int, QString >(i,line));

You're attempting to insert into a map using an invalid (uninitialized) iterator. Are you running this in debug or release? You should get an assertion in debug.

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