Search code examples
cdangling-pointer

why is this dangling pointer in C?


why ptr is dangling pointer. I know "ch" is out of scope, but address of ch is still valid out of inner block. And when I print *ptr I get correct value i.e. 5.

void main()
{
   int *ptr;
   
   {
       int ch = 5;
       ptr = &ch;
   } 
  
  
  printf("%d", *ptr);
}

Solution

  • ptr is a pointer to memory that doesn't belong to you anymore and that can contain anything including the value you expect. The 5 you see ist just a leftover, it could be overwritten anytime. What you see here is undefined behaviour.

    In this simple case code generated by the compiler is most likely the same as the code the compiler would generate for this program (which is perfectly legal) and that's probably the reason you get 5:

    void main()
    {
       int *ptr;
       
       int ch = 5;
       ptr = &ch;
       
       printf("%d", *ptr);
    }
    

    Consider this case which is a bit more complicated:

    int *foo()
    {
        int ch = 5;
        return &ch;
    }
    
    void main()
    {
      int* ptr = foo();
    
      printf("%d ", *ptr);
      printf("%d ", *ptr);
    }
    

    Here the output might be something like this:

    5 45643
    

    The first time you may get 5 because the memory has not yet been overwritten, the second time you get something else because in the meantime the memory has been overwritten.

    Be aware that the output could be anything else or it could even crash, because this is undefined behaviour.

    Also read this: Can a local variable's memory be accessed outside its scope?, this article is for C++ but it also applies to the C language.