when does c++ allocate/deallocate string literals

帅比萌擦擦* 提交于 2019-12-28 16:06:32

问题


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;
}

回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/1971183/when-does-c-allocate-deallocate-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!