简体   繁体   中英

What happens if a pointer runs out of scope

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?

Function addFive is normal by itself but it should be written like this:

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

And there is no any problem with pointer's b scope because pointer itself is just a local variable.

Real problem in your code is that you didn't allocate memory for your integer and trying to access uninitialized memory through pointer nbr which leads you to undefined behaviour. On my machine I have segmentation fault at this line:

*nbr = 3;

Your main should be rewritten like this:

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

Then you can reliably expect '8' in your output.

Why does this code not give a segmentation fault?

Your expectation for segmentation fault is correct. But all random accesses of memory won't create segmentation fault. If the randomly accessed memory have any protection rights then only it creates segmentation fault . If it do not have any protection then you can access the memory without any problem but with an undefined behavior , because you could not assume the contents in the random memory. A good pictorial explanation is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM