gpt4 book ai didi

c++ - 指针的内存使用情况

转载 作者:IT王子 更新时间:2023-10-28 23:35:58 26 4
gpt4 key购买 nike

请看下图。更改 p1 的值后,现在它指向 B2 内存位置。阴影内存段发生了什么?据我所知,它将一直保留到代码块完成执行。那些被垃圾的内存段可以再次用于程序执行吗?

char *p1 = "String";
char *p2 = "Another";
p1 = p2;

问题标题可能具有误导性。我找不到这个问题的好标题。 enter image description here

最佳答案

What happened to the shaded memory segment? As i know It will remain until code block finished its execution.

根据 §2.13.5/8,字符串文字具有静态存储持续时间:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

这意味着,根据 §3.7.1/1,它们将持续整个程序:

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).

附带说明,您应该真正将字符串文字分配给 char const*char const[],而不是 char*。它主要在编译器中工作的原因是出于向后兼容性的原因,而在 C++11 中它已被弃用。


Can those garbaged memory segments be reused again for program execution?

根据 §2.13.5/16 未指定它们是否被重复使用:

Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified. [ Note: The effect of attempting to modify a string literal is undefined. — end note ]

关于c++ - 指针的内存使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33012680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com