Re: assigning a pointer the address of local variable
- From: Kenneth Brody <kenbrody@xxxxxxxxxxx>
- Date: Wed, 23 Aug 2006 11:00:55 -0400
Keith Thompson wrote:
[... code which stores &localvar in globalvar ...]
"Sourav" <soura.jagat@xxxxxxxxx> writes:
Suppose I have a code like this,
In most of the compilers I use (GCC, MSVC++, lcc..) this program runs
allright printing an address and the correct value 4. But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?
No, it isn't. When s reaches the end of its lifetime (at the end of
foo(), the value of p becomes indeterminate. Dereferencing p, or even
looking at its value, invokes undefined behavior. (The latter isn't
likely to cause any visible problems on most systems, but you should
still avoid it.)
<mode pedant=on>
"To assign a global variable the address of a local variable" is fine.
It's the use of that variable after the function exits that is UB.
</mode>
Imagine a situation where the function calls other functions which use
the global variable. This is not a problem. (Well, some people would
argue that it's a "problem" in the sense that "you shouldn't use global
variables". But that's a different issue entirely.)
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:ThisIsASpamTrap@xxxxxxxxx>
.
- References:
- assigning a pointer the address of local variable
- From: Sourav
- Re: assigning a pointer the address of local variable
- From: Keith Thompson
- assigning a pointer the address of local variable
- Prev by Date: Re: routine to return number of rows and columns in a matrix
- Next by Date: Re: Is it legal?
- Previous by thread: Re: assigning a pointer the address of local variable
- Next by thread: Re: assigning a pointer the address of local variable
- Index(es):
Relevant Pages
|