I have the following code, and I am wondering why it works as it does:
void addFive(int* a) {
int* b;
b = a;
*b = *b + 5;
}
int main(int argc, char** argv) {
int* nbr;
*nbr = 3;
addFive(nbr);
std::cout << *nbr << std::endl;
return 0;
}
This produces an output of 8.
I am wondering why? The pointer int* b
runs out of scope at the end of the addFive function. Furthermore, int* b
has no knowledge about the existence of int* nbr
(one advantage of smart pointers). I expected the code to create a segmentation fault in the line std::cout << *nbr << std::endl;
Why does this code not give a segmentation fault?