1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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,276
    Likes Received:
    364
    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:
    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
    thanks.
     

Share This Page