简体   繁体   English

什么时候c ++分配/解除分配字符串文字

[英]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? 在此示例中,在程序的生命周期中,字符串文字“hello”何时被分配和释放?

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

The string literal is initialised into read-only memory segment by the compiler. 字符串文字由编译器初始化为只读内存段。 There is no initialisation or removal done at run-time. 在运行时没有初始化或删除。

它们未分配,而是存储在可执行文件的DATA段中。

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. 假设存在操作系统,则在OS加载可执行文件时分配包含字符串文字的内存,并在OS卸载可执行文件时解除分配。 Exactly when this happens depends on the type of executable (program, shared library, etc.) and the OS. 究竟何时发生这种情况取决于可执行文件的类型(程序,共享库等)和操作系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM