Dereferencing pointers without pointing them at a variable

前端 未结 4 1297
野趣味
野趣味 2020-12-02 01:14

I\'m having trouble understanding how some pointers work. I always thought that when you created a pointer variable (p), you couldn\'t deference and assign (*p = value) unle

4条回答
  •  心在旅途
    2020-12-02 01:48

    Not to seem like a "Me too!" answer, but the other answers don't answer your core question:

    Okay I get that the first one shouldn't work either, but why does it. That's what I'm after.

    In this case, you are invoking Undefined Behavior. Both the C and C++ standards are clear that when a variable is uninitialized, its contents are undefined. And when it says undefined, it means, unknown. These pointers could contain literally anything. Because they're uninitialized, they contain whatever memory happened to be at the location that the compiler chose for those two variables.

    In this case, your first variable just happens to contain a pointer that points within your program's memory space. The second just happens to contain a pointer that points outside your program's memory space. It could be anything from a null pointer to a pointer to your main function. Whatever it is, it's irrelevant: You don't need to know or care, because it's garbage. You're expected to write over it anyway.

    It's a common expression among C programmers that invoking undefined behavior causes demons to fly from your nose. This is because the C standard states quite clearly that when behavior is not defined, the compiler is free to do anything it wants to do. And that includes launching nuclear missiles, resetting your bank account to zero, or, yes, causing winged creatures to flitter forth from your nasal cavity.

提交回复
热议问题