In Java, an object will remain in existence so long as
there is a reference to it. In C, an object may go out of
existence even if there are pointers to it — the
programmer is entirely responsible for ensuring that
pointers contain valid addresses (either 0
, or the address of an existing object)
when used. This badly written function returns a pointer
to an integer variable:
int *badfunc(void)
{
int x = 18;
return &x; /* Bad - x
won't exist after the call has finished. */
}
The pointer returned by badfunc()
is invalid because the variable
no longer exists. Although the memory for the variable
still exists, it is no longer allocated to that variable,
and it might not even be accessible any more. Do
not dereference a dangling pointer! Although the
likely result is that it may appear to work, it could
fail at once if the memory is no longer accessible, or if
it has been corrupted. It might quietly fail later if you
attempt to overwrite it, thus corrupting what it is now
being used for.