Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   dangling pointer (http://www.go4expert.com/forums/dangling-pointer-t3893/)

chopin17 16Apr2007 13:18

dangling pointer
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 16Apr2007 13:33

Re: dangling pointer
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 16Apr2007 13:38

Re: dangling pointer
then why it doesn't crash.
I compile it with 2 different compilers and it doesn't crash
why is that ???

DaWei 16Apr2007 15:49

Re: dangling pointer
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 16Apr2007 16:11

Re: dangling pointer

All times are GMT +5.5. The time now is 09:54.