Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does c++ allocate/deallocate string literals

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;
}
like image 359
user236215 Avatar asked Dec 28 '09 19:12

user236215


2 Answers

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

like image 82
Martin York Avatar answered Sep 18 '22 10:09

Martin York


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

like image 29
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 10:09

Ignacio Vazquez-Abrams