7

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;
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
user236215
  • 7,278
  • 23
  • 59
  • 87

3 Answers3

16

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
  • 257,169
  • 86
  • 333
  • 562
  • 1
    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 Dec 28 '09 at 20:00
  • 1
    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 Dec 28 '09 at 20:04
  • @Thomas. I don;t believe any compiler would copy the string onto the stack that seems rather a redundant operation to me. – Martin York Dec 28 '09 at 20:09
  • @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 Dec 28 '09 at 20:12
3

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    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 Dec 28 '09 at 20:02
1

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
  • 23,871
  • 6
  • 54
  • 65