I'm a newb with c++, so forgive me, I've tried to make this example as simple as possible. I'm running into a segmentation fault in trying to assign a pointer's target value to another pointer's target value. What I've found is, the fault can be fixed, but only if I declare an extra variable which I never use, and which has no use in the program. Can anyone explain what's going on here?
int main() {
int x = 3;
// bool y; //Although y is never used, uncommenting this removes the fault!
int *b1, *b2;
b1 = &x;
*b2 = *b1;
cout << "b1 @ " << b1 << " value: " << *b1 << endl; //b1 @ 0x16fa3f518 value: 3 [when y is declared]
cout << "b2 @ " << b2 << " value " << *b2 << endl; //b2 @ 0x16fa3f520 value 3 [when y is declared]
return (0);
}
The result is a segmentation fault unless I declare another variable - it doesn't matter what type and it doesn't matter if it's ever assigned. In this example, declaring bool y
removes the fault.
I'm guessing this has something to do with the program not assigning enough memory to deal with a second pointer address, but why is that the case and how does one address it?