Reputation: 3
I am new to C++ and experimenting with using pointers to return a values. I have written up a simple program, but I cannot understand why it crashes.
main.cpp
int main() {
bool *pMyBool;
bar myBar;
myBar.foo(pMyBool);
cout << *pMyBool << endl;
return 0;
}
bar.cpp
int bar::foo(bool *pMyBool) {
bool myBool = true;
*pMyBool = myBool;
return 0;
}
output
1
//then it crashes
Upvotes: 0
Views: 311
Reputation: 1
In C++, you don't want to use pointers in your case, but to use references:
int bar::foo(bool &MyBool) {
MyBool = true;
return 0;
}
Of course, you'll just call from your main
bool MyMainBool = false;
bar.foo(MyMainBool);
Upvotes: 3
Reputation: 64875
it's because myBool is allocated in the "stack" (local variables); when the function foo exits, the stack associated with foo is released therefore the pointer pMyBool is pointing to a memory address that is no longer valid.
Upvotes: -1
Reputation: 6616
pMyBool
is not pointing to any valid location. SO you cannot dereference it.
You should first allocate memory, and make the pointer, point to it. bool *pMyBool = new bool;
and later deallocate memory. delete pMyBool;
Upvotes: 2
Reputation: 754280
You don't initialize pMyBool
in main()
, so it points at random memory, and then the program crashes because the random memory isn't valid memory.
One possible fix:
int main() {
bool value;
bool *pMyBool = &value;
bar myBar;
myBar.foo(pMyBool);
cout << *pMyBool << endl;
return 0;
}
With pointers, you always need to ensure you initialize them to point somewhere before you try using them. Always!
Upvotes: 4