c++ - What happens if a pointer runs out of scope -


i have following code, , wondering why works 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 output of 8.

i wondering why? pointer int* b runs out of scope @ end of addfive function. furthermore, int* b has no knowledge existence of int* nbr (one advantage of smart pointers). expected code create segmentation fault in line std::cout << *nbr << std::endl;

why code not give segmentation fault?

function addfive normal should written this:

void addfive(int* a) {    *a += 5; } 

and there no problem pointer's b scope because pointer local variable.

real problem in code didn't allocate memory integer , trying access uninitialized memory through pointer nbr leads undefined behaviour. on machine have segmentation fault @ line:

*nbr = 3; 

your main should rewritten this:

int* nbr = new int(3); addfive(nbr); std::cout << *nbr << std::endl; return 0; 

then can reliably expect '8' in output.


Comments