PDA

View Full Version : Segmentation fault when creating new QString



di_zou
28th September 2009, 21:11
I have:



//Node.cpp

#include "Node.h"

Node::Node(QWidget *parent)
: QLabel (parent) {
}

void Node::setName(string picName) {
nodePicName = new QString(QString::fromStdString(picName));
}


and then in my "Node.h" file I have:



class Node : public QLabel {

Q_OBJECT

public:
Node(QWidget *parent = 0);
virtual ~Node();
void setName(string picName);

private:
QString *nodeName;
}:


I am getting a segmentation fault at where I have:


nodePicName = new QString(QString::fromStdString(picName));

franz
28th September 2009, 21:24
I don't know what exactly goes wrong, but why don't you just use


QString nodeName;


and



void setName(std::string name)
{
nodeName = QString::fromStdString(name);
}


or what would have my preference



void SomeClass::setName(const QString &name)
{
nodeName = name;
}


then call the function using



obj.setName(QString::fromStdString(somestring));


There is no need to use pointers for QStrings since they implement implicit sharing, which basically means that if you copy a string, you only copy a reference to the data. When you start to change the contents, then a deep copy is made. This design approach makes it easier for you to code, less error prone (less memory leaks) and more readable.

di_zou
29th September 2009, 17:53
So I changed it around to this:


void Node::setName(const QString &name)
{
nodeName = name;
}

and


class Node : public QLabel {

Q_OBJECT

public:
Node(QWidget *parent = 0);
virtual ~Node();
void setName(const QString &name);

private:
QString nodeName;
};

but I still get a seg fault inside the setName method.

di_zou
29th September 2009, 18:07
Nvrmnd got it working. Thank you.