PDA

View Full Version : Segmentation Fault



Ryan Riffle
16th January 2011, 19:11
I am parsing every topLevelItem of QTreeWidget and adding it's text to a QList. But I am getting a segmentation fault when I try to add the text to the list.

Here is my code:


QList<QString> ulist;
QTreeWidgetItem *item;

for(int x=0; x<ui->treeWidget->topLevelItemCount(); x++)
{
item = ui->treeWidget->topLevelItem(x-1);
ulist.append(item->text(0));
}


Thanks in advance to anyone that may be able to help.
-Ryan

squidge
16th January 2011, 19:18
Is ui->treeWidget->topLevelItem(-1) a valid index?

Also, you do not seem to check if the item is valid before adding it to the list

Ryan Riffle
16th January 2011, 19:34
Thanks for your reply,

ui->treeWidget->topLevelItem(x-1) is a valid index because it starts with the first item on the list, so the loop wouldn't have started unless there was atleast one item.

But how do you check if the item is valid?

squidge
16th January 2011, 20:27
Yes, and x starts at zero, so zero - 1 is -1.

So is ui->treeWidget->topLevelItem(-1) a valid index?

Secondly, the above function will return NULL if it's invalid, and if you try to dereference a NULL pointer, well, you can guess what happens.

Ryan Riffle
16th January 2011, 20:52
Thank you very much squidge.
I guess i didn't totally take in or understand what you posted the first time.

Here is my new code that runs fine.


QList<QString> ulist;
QTreeWidgetItem *item;

for(int x=0; x<ui->treeWidget->topLevelItemCount(); x++)
{
item = ui->treeWidget->topLevelItem(x);

if(item->text(0) != "")
{
ulist.append(item->text(0));
}
}

:p I can't believe i never noticed that.

Thanks again.