dangling pointer

Discussion in 'C' started by chopin17, Apr 16, 2007.

  1. chopin17

    chopin17 New Member

    Joined:
    Apr 16, 2007
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    Someone help please ...

    struct node
    {
    int d;
    struct node *next;
    }

    struct node * create(int val)
    {
    struct node nd, *ndPtr;
    nd.d = val;
    nd.next = NULL;
    ndPtr = &nd;
    return ndPtr;
    }

    Is ndPtr a dangling pointer ???
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Dangling pointer is a pointer which points to an object that no longer exists and your one is a classic case of the same. It points the local variable nd which does not exist when gone out of scope of create but it returns the pointer to nd.
     
  3. chopin17

    chopin17 New Member

    Joined:
    Apr 16, 2007
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    then why it doesn't crash.
    I compile it with 2 different compilers and it doesn't crash
    why is that ???
     
  4. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    It doesn't have to crash. It can trash the latest autovariable which is now using that memory, which can be a very subtle failure. Read up on automatic variables and scope.
     
  5. chopin17

    chopin17 New Member

    Joined:
    Apr 16, 2007
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice