Fog Creek Software
Discussion Board




Memory Allocation

Where is the memory allocated when I do the following.

char *str = "hello world";

Who will clean it up ? Is it in function stack ? How long the pointer 'str' will be valid ?

Ramachandra Pisharody
Wednesday, August 04, 2004

That creates a pointer variable on the stack that points to a string in the data segment of the executable, typically.

Literal strings are stored somewhere in the executable image which is located into memory when the program is run.

So it will persist for the entire time the program is run (ignoring paging and stuff like that).  It is "static" (in quotes because that word has a lot of meanings).

But the thing you probably care about is that you never have to worry about deallocating the string.

Roose
Wednesday, August 04, 2004

That's Fantatstic..!.

Ramachandra Pisharody
Wednesday, August 04, 2004

It's also constant, so you can't do this:
*str[3] = 'y'

Furious George
Wednesday, August 04, 2004

Depends on the compiler, actually. With gcc, you can use -fwritable-strings to enable mutation of string constants.  With MSVC, I think string constants are writable *unless* you supply /Gf to cl.exe, although that's just going by the /? output, I haven't checked.

Iago
Wednesday, August 04, 2004

To expand on Roose's comment

char * str1 = "Hello" ;

void Func( void )
{
char * str2 = "Hello" ;
}


The string "Hello" is stored in the program's image. There may or may not be more than one copy of it depending on the compiler/linker/options. (I'm not sure what the C and C++ standards say but I've definitely seen both behaviours).

str1 is a global variable, stored where-ever the compiler puts globals.

str2 is stored on the stack

In neither case do you need to deallocate.

And it might be a good idea to make these into consts, especially if the compiler/linker/options folds both Hellos into one copy.

S. Tanna
Wednesday, August 04, 2004

*  Recent Topics

*  Fog Creek Home