Re: assigning a pointer the address of local variable



Keith Thompson wrote:

"Sourav" <soura.jagat@xxxxxxxxx> writes:
Suppose I have a code like this,
[... code which stores &localvar in globalvar ...]

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>


.



Relevant Pages

  • Re: compiler back-end development?
    ... with GCC and MSVC. ... I could try to use my own own compiler, but at this stage its Win64 support ... a lot more of my code needs proper tests, and a lot more of my code needs ...
    (comp.compilers)
  • switching mex compiler from lcc to MSVC - need a couple of tips!
    ... For compiling mex files, I want to switch from LCC to MSVC, because I want to ... I don't have MSVC++ 2005 v8 Pro package, but my needs are very simple and I ... I don't know about anything about resource compilers and manifest tools. ...
    (comp.soft-sys.matlab)
  • Re: 128 bit integers is on topic
    ... since the code doesn't run under gcc, it is specific to lcc-win etc. ... defines int128_t and uint128_t (at least for my compiler). ... it is worth noting that MSVC does not have this header. ... since my internal mental projections tend to be full 3D ...
    (comp.lang.c)
  • Re: gcc question
    ... > MSVC is likely to be slightly faster because it is ... > MSVC standard will be slower than Gcc because it doesn't do any ... > MSVC Std is fairly cheap. ... > Gcc and MSVC have good conformance. ...
    (microsoft.public.vc.language)
  • Re: c compilation - gcc vs visual c
    ... vast performance difference and my code is not at all ... msvc by default uses their own O2. ... GCC is not that far behind MSVC. ... system to dictate all the various platform-dependent optimizations; ...
    (comp.lang.c)