Scoping question in C
Kevin Cozens
kcozens-qazKcTl6WRFWk0Htik3J/w at public.gmane.org
Fri Jun 10 20:54:16 UTC 2005
William Park wrote:
>But, if the static string lives for the duration of the program, then
>pointer to it should always be valid, no? Eg.
>
> char *func2()
> {
> char *y;
>
> y = "something inside";
> return (y);
> }
>
>Here, 'y' (or, what the function returns) should be valid for entire
>program.
>
>
In func2, y is allocated on the stack and only exists while executing
the code of func2. After the return, the variable y "disappears" as the
stack space used by the function is released. The value returned by
func2 remains valid since the value assigned to y was that of an object
with a fixed address.
Be very careful in doing what you show in the above example. If you
don't pay close attention to whether the address pointed to by y still
exists after the function returns you can easily find yourself starting
at a seg fault message when running your program.
--
Cheers!
Kevin. (http://www.interlog.com/~kcozens/)
Owner of Elecraft K2 #2172 |"What are we going to do today, Borg?"
E-mail:kcozens at interlog dot com|"Same thing we always do, Pinkutus:
Packet:ve3syb at ve3yra.#con.on.ca.na| Try to assimilate the world!"
#include <disclaimer/favourite> | -Pinkutus & the Borg
--
The Toronto Linux Users Group. Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml
More information about the Legacy
mailing list