简体   繁体   中英

why this pointer does not give me a garbage value

In my code, I increment address of the *p which address doesn't contain any value.so, why this p variable doesn't return me a garbage value.

#include <stdio.h>
int main()
{
    int a=4;
    int *p=&a;
    p++;
    printf("%d ",*p);

    return 0;
}

why this pointer does not give me a garbage value

It probably does. The behaviour of the program is undefined.

I recommend thinking why you thought that you didn't get a garbage value. That should lead you to a deeper understanding.

Note that technically getting a garbage value isn't guaranteed. It's entirely possible that you get no output at all, or that the program crashes or anything else. But if you do get output, it will be garbage.

This is an undefined behavior so it may show you some values that may seem to be valid but is not. Here is an element of undefined behavior documentation and here

There are no "garbage" values. According to the c++ standard, a program that contains undefined behavior has... well... undefined behavior. The output could be anything.

You are not guaranteed to get any meaningful output. Though, that does not imply that the output you get is guaranteed to be meaningless (or "garbage" or whatever you want to call it).

It could be 4 because a holds that value, it could be 4 because that value happens to be in some register. You have no way to tell why you get the output you get by looking only at the code and the output. Thats because the C++ standard does not specifiy what the program does at runtime when you dereference an invalid pointer, ie when your code invokes undefined behavior anything can happen.

If you want to know where the output actually comes from you can look at the assembly. For a simpler code:

int main() {
    int* p;
    return *p;
}

gcc -O3 :

main:
        mov     eax, DWORD PTR ds:0
        ret

When running the code, it segfaults. Thats one possible outcome. Given that code, anything else is possible as well.

Because you increment the pointer , not the value it points to.

Then *p points into the memory after a . That place is on the stack and youfind some random(?) value there.

Define another variable b with some other value after a and you will most likel see that value.

It's returning garbage value

 468024888

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