Re: function return pointer of int?
Puppet_Sock <puppet_sock@hotmail.com> writes:
On Nov 5, 4:26?am, vipps...@gmail.com wrote:
[...]
int *foo(int i) { return &i; }
However even evaluating foo(anything) invokes undefined behavior,
since the object pointed to by the pointer is over its lifetime, and
the pointer becomes indeterminate. (either unspecified value or trap
representation)
It only becomes undefined if you try to deref the
pointer that gets returned, because it's a pointer
to a local variable, which has gone out of scope
by the time foo returns. There is no problem with
taking the address, or passing the address around.
But if you try to manipulate things through that
address, you open the gates of undefined.
(Ok, whose sock-puppet are you?)
You're mistaken. If you have a pointer to an object, and that object
then ceases to exists, then the pointer value becomes indeterminate,
and any attempt to evaluate the pointer invokes undefined behavior.
For example:
int *p = malloc(sizeof *p);
assert(p != NULL); /* just for this example */
free(p);
p; /* undefined behavior */
On most implementations, nothing bad will actually happen; that's just
one possible manifestation of undefined behavior.
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"