int main(){
MyBase *mb;
int choice;
cout << "Select: ";
cin >> choice;
switch (choice) {
case 1:
mb = new Test1();
break;
case 2:
mb = new Test2();
break;
case 3:
mb = new Test3();
break;
case 4:
mb = new Test4();
break;
case 5:
mb = new Test5();
break;
case 6:{
LinkTest t;
t.start();
break;
}
default:
return 0;
}
if(mb != 0){
mb->start();
delete mb;
}
return 0;
}
If choice is 6, why am I getting a segmentation fault when checking if mb is NULL?
I am new to c++ and just doing some exercises.
How can I fix this without affecting the class LinkTest?
Thanks.
When you declare variables inside function scope, they are normally whats called “stack variables”. This means they reside in stack-memory which typically contains lots of “garbage” from previous use. Hence, when not initializing the ‘mb’ variable upon declaration, the initial value is undefined (whatever happened to be lying around on that spot in the stack), typically non-zero.
Therefore you should initialize mb upon declaration:
As an aside, I noticed that the ‘case 6:’ inside the ‘switch’ doesn’t set mb to anything…