PDA

View Full Version : Crashing without qDebug() ?



xtreme
5th August 2008, 16:34
Hello,
In my code I am calling a void-function which creates some variables. However it will crash if I use it like this:


Boxes();
emod.verticalLayout->addWidget(boxes[0]);
emod.verticalLayout->addWidget(boxes[1]);
emod.verticalLayout->addWidget(boxes[2]);
emod.verticalLayout->addWidget(boxes[3]);
emod.verticalLayout->addWidget(boxes[4]);

If I use this:


qDebug() << "a1";
Boxes();
qDebug() << "a2";
emod.verticalLayout->addWidget(boxes[0]);
emod.verticalLayout->addWidget(boxes[1]);
emod.verticalLayout->addWidget(boxes[2]);
emod.verticalLayout->addWidget(boxes[3]);
emod.verticalLayout->addWidget(boxes[4]);

It does not crash.

Function boxes() in the header:


public:
void Boxes();


the code of boxes() is:


void TableEditor::Boxes(){
boxes.clear();
int x;
for(int i=0;i<15;i++){ //create 15 qcheckboxes;
QCheckBox *temp = new QCheckBox(Dialog);
temp->setObjectName("");

if(x < mod.size()){
qDebug() << "added text" << mod[x];
temp->setText(mod[x]);
temp->setVisible(true);
x++;
}else{
temp->setText("");
temp->setVisible(true);
}

boxes.append(temp);
}
}

boxes is a QLIST<QCheckbox*>. and mod is a QLIST<QString>.
What can I do to solve this. I do not want to use qDebug() to fix the function. Could somebody tell me what is wrong and how I can solve this?
any help would be appreciated.

jpn
5th August 2008, 16:35
You forgot to initialize "int x".

xtreme
5th August 2008, 16:40
Thanks, it seems to be the solution. I always thought when defining a standart variable like a int that there was no need to add =0 to it. Still a bit odd that when using qDebug() it does not crash.

caduel
5th August 2008, 18:01
Welcome to the C/C++ joys of undefined behaviour.

Your variable x was not initialized. Its value therefore 'random', which means: whatever value the stack had at the location reserved for x.
Calling qDebug() seems to have had a side effect of leaving some value >= 0 at that position. (Pure coincidence...).
Without qDebug() the value happend (pure good luck again) to be negative (I guess) which lead to a crash in accessing mod[x].

You can and should not depend on something like that ;-)
Your compiler should have printed a warning for the forgotten initialization. Try to fix all warnings. Bad bugs tend to hide behind and among them. It takes way less time to fix the warnings than to fix the bugs hiding there afterwards.
And code that compiles with lots of warnings give an unpleasant feeling and lowers trust in that code. (I would not want to deliver code that compiles with thousands of warnings...)

HTH