views:

359

answers:

3

When is the string literal "hello" allocated and deallocated during the lifetime of the program in this example?

init(char **s)
{ 
  *s = "hello";
}
int f()
{
  char *s = 0;
  init(&s);
  printf("%s\n", s);
  return 0;
}
+2  A: 

They are not allocated but instead stored in the DATA segment of the executable.

Ignacio Vazquez-Abrams
FYI, the C and C++ languages don't require a *DATA* segment. The specification states that string literals are constants, but leaves their storage area up to the translator.
Thomas Matthews
+6  A: 

The string literal is initialised into read-only memory segment by the compiler. There is no initialisation or removal done at run-time.

Martin York
The compiler may copy the contents of the string literal into *local storage* (the stack), thus there is some initialization. To prevent this, I declare variables as `const static char text[] = "hello";`. Also, the read-only segment may also be the executable segment.
Thomas Matthews
String literals might be in read-only memory, but that is compiler dependent. So modifying a string literal, like in the code in the question, has undefined behavior but it might work.
David Nehme
@Thomas. I don;t believe any compiler would copy the string onto the stack that seems rather a redundant operation to me.
Martin York
@Thams, @David: Yes the compiler may choose not to use read-only segment (as said an implementation detail). But from the programmers standpoint you should always consider it as a read-only as the type is actually 'char const*' and is only converted to 'char*' for backward compatability with C, and as noted any modification is undefined behavior.
Martin York
A: 

Assuming there is an operating system, the memory containing the string literal is allocated when the OS loads the executable and deallocated when the OS unloads the executable. Exactly when this happens depends on the type of executable (program, shared library, etc.) and the OS.

bk1e