santosh said:
Thank you all for your clear replies.
To sum up, if I understand correctly, good programming implies
that a pointer must either be NULL or must contain a known
value, returned by malloc() and co.
A pointer can also contain the address of a declared object. If
you're not careful, this can cause similar problems if the object
ceases to exist before the pointer does. For example:
int *func(void)
{
int local_var;
return &local_var;
}
local_var ceases to exist when func() returns, but the caller now has
a pointer to this nonexistent object. If the caller attempts to use
this pointer value, it will invoke undefined behavior.
If you need to do this kind of thing, there are several workarounds.
You can declare local_var as static (which means every call to func()
will return the same address), or you can allocate the space with
malloc() (which means it's up to the caller to free() it), or you can
pass a pointer *into* the function and let the function assign a value
to the pointed-to object (which means the caller has to know -- or
guess -- how much space to allocate). This isn't likely to be an
issue for a pointer to int, but it's common when you want your
function to return an array, such as a string.