dangling pointer

chopin17's Avatar, Join Date: Apr 2007
Go4Expert Member
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 ???
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
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.
chopin17's Avatar, Join Date: Apr 2007
Go4Expert Member
then why it doesn't crash.
I compile it with 2 different compilers and it doesn't crash
why is that ???
DaWei's Avatar, Join Date: Dec 2006
Team Leader
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.
chopin17's Avatar, Join Date: Apr 2007
Go4Expert Member
thanks.