Scoping question in C

John Vetterli jvetterli-zC6tqtfhjqE at public.gmane.org
Thu Jun 9 23:34:50 UTC 2005


>From a standards point of view:

"The standard" (by which I mean ISO/IEC 9899:1999 (google for a pdf) 
section 6.4.5 "String Literals") says it has "static storage duration". 
It also says attempting to modify the string results in undefined 
behaviour.

>From an implementation point of view:

String literals are stored in the process' ro-data segment, so the data 
that your pointer will point to is created when the kernel loads the 
program into memory, and will persist for the life of the process.  Also, 
since the data is in a read-only segment(*), a const-happy programmer 
would use "const char *x;".

(*) I think there's a way to get gcc to put the string (or all strings) 
into the data segment, allowing you to overwrite it.  I have never looked 
into how to do this, though.

JV


On Thu, 9 Jun 2005, William Park wrote:

> 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