Confusion about the fact that uninitialized pointer points to anywhere

前端 未结 1 1347
猫巷女王i
猫巷女王i 2020-12-22 13:45
#include 

int main(void)
{
    int *ptr;
    printf(\"%p\", ptr); // Error: uninitialized local variable \'ptr\' used
                       // Outpu         


        
相关标签:
1条回答
  • 2020-12-22 13:48

    The contents of an unitialized auto variable (pointer type or otherwise) are indeterminate; in practice, it's whatever was last written to that memory location. The odds that this random bit pattern corresponds to a valid address1 in your program are pretty low; it may even be a trap representation (a bit pattern that does not correspond to a legal value for the type).

    Attempting to dereference an invalid pointer value results in undefined behavior; any result is possible. Your code may crash outright, it may run with no apparent issues, it may leave your system in a bad state.


    1. That is, the address of an object or function defined in your program, or a dynamic object allocated with malloc or similar.

    0 讨论(0)
提交回复
热议问题