Scoping question in C

Jian (James) Zhou jameszhou2000-PkbjNfxxIARBDgjK7y7TUQ at public.gmane.org
Fri Jun 10 20:24:57 UTC 2005


That depends how "something" is allocated from memory. Since "x" is declared
outside of the function body, "x" is a global variable which can be accessed
by all functions ("static" only affects the scope of visibility in this
case, and it won't change the fact that "x" is a global variable living in
data section).

Here within the function, if the memory that holds the string is a local
variable (i.e. it lives in stack), the memory will not be available after
the function is returned. Thus, the pointer "x" is pointing to an invalid
address. However, if the memory that holds the string is dynamically
allocated within the function, and it is not "freed". Then, the "x" is
pointing a valid memory space. In this case, you can still use "x" to access
the string even after the function returns.

James Zhou


----- Original Message ----- 
From: "William Park" <opengeometry-FFYn/CNdgSA at public.gmane.org>
To: <TLUG-lxSQFCZeNF4 at public.gmane.org>
Sent: Thursday, June 09, 2005 6:48 PM
Subject: [TLUG]: Scoping question in C


> I have question regarding scope of static string inside C function.
> Suppose I have
>
>     char *x;
>
>     int func ()
>     {
> x = "something";
> return (1);
>     }
>
> where 'x' is global variable being used elsewhere.  Can I use 'x' after
> func() exits?  That is, is 'x' still pointing to string "something"?
>
> -- 
> William Park <opengeometry-FFYn/CNdgSA at public.gmane.org>, Toronto, Canada
> ThinFlash: Linux thin-client on USB key (flash) drive
>    http://home.eol.ca/~parkw/thinflash.html
> --
> 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
>
--
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