Re: Why this code is working
- From: Simon Biber <news@xxxxxxxxx>
- Date: Tue, 01 Nov 2005 01:24:06 +1100
jammie_linux@xxxxxxxxx wrote:
But when a function returns, the compiler reclaims all the memory assigend to the local variables. By this theory, isn't it possible that the memory where the string "This is local to the function" was stored, would also be reclaimed. In that case, the main's function str will be pointing at a totally meaningless position.
No, because the string "this is local to the function" is *not* local to the function. String literals always have static duration, no matter where you declare them. The string literal continues to exist even after the function returns.
If you had instead used the string literal as an initialiser for a local array, then it would have returned an invalid pointer as you seem to expect.
Compare the following functions:
char *funct1()
{
char *str = "This is a string literal with static duration.";
return str;
}char *funct2()
{
char str[] = "But this one is used to initialise a local array.";
return str;
}The [] in funct2 make all the difference. Funct1 returns a valid pointer, but funct2 returns an invalid pointer.
-- Simon. .
- Prev by Date: Re: need of a sprintf like function...
- Next by Date: Re: Quick questions...
- Previous by thread: Re: need of a sprintf like function...
- Next by thread: Re: Why this code is working
- Index(es):
Relevant Pages
|