PDA

View Full Version : Segmental fault when using QValueVector



luffy27
29th March 2007, 06:37
I'm using Qt3.
The compelling process is OK, but when I run the application I have a segment fault(or segmental fault, I can't remember what is exactly called).
The code is below:

oridata.h


#ifndef ORIDATA_H
#define ORIDATA_H

#include <qnamespace.h>
#include <qstring.h>
#include <qvaluevector.h>

class OriData;
typedef QValueVector<OriData> OriDataVector;

class OriData
{

public:
OriData(double X=0.0, double Y=0.0) {m_X=X;
m_Y=Y;}
private:
double m_X;
double m_Y;
};

mainwindow.h


#include "oridata.h"

class MainWindow:public QMainWindow
{
public:
enum{MAX_ORIDATA=100};
...........................
private:
...........................
OriDataVector m_oriData;
};

mainwindow.cpp


MainWindow::MainWindow(const QString &filename)
:QMainWindow(0,0,WDestructiveClose)
{
......................
init();
m_oriData.resize(MAX_ORIDATA);
...................
}

void MainWindow::init()
{
..................................
..................................
textEdit = new QTextEdit(this,"textedit");
textEdit->setTextFormat(Qt::PlainText);
textEdit->setFocus();
this->setCentralWidget(textEdit);

QString str;
for(int i=0; i<MAX_ORIDATA; i++)
{
QString strX,strY;
double x = m_oriData[i].getX();
double y = m_oriData[i].getY();
strX = strX.setNum(x,'f');
strY = strY.setNum(y,'f');
strX = 'X'+strX;
strY = 'Y'+strY;
str = strX+strY;
textEdit->append(str);
}
}

I guess, the error maybe occurred in the MainWindow::init(), in the "for" circle, because when I comment out the "for" circle, the application runs OK without any error.

I'm a newbie please help me. Thanks a lot!

jpn
29th March 2007, 07:15
Swap these two lines:

m_oriData.resize(MAX_ORIDATA); // <-- resize the vector before
init(); // <-- the for loop which expects it to have size of MAX_ORIDATA

luffy27
30th March 2007, 06:14
Thanks jpn, that is correct.
Now it is Ok.