简体   繁体   English

C如何处理本地字符串文字的内存?

[英]How does C work with memory of local string literals?

Consider this function: 考虑这个功能:

void useless() {
   char data[] = "aaa";
}

From what I learned here , the "aaa" literal lives to the end of the program. 根据我在这里学到的, "aaa"文字一直存在到程序的最后。 However, the data[] (initialized by the literal) is local, so it lives only to the end of the function. 但是, data[] (由文字初始化)是本地的,因此它仅存在于函数的末尾。

The memory is copied, so the program needs 4B for the literal, 4B for the data and sizeof(size_t) bytes for the pointer to data and sizeof(size_t) for the pointer of the literal - is this true? 内存被复制,因此程序需要4B用于文字,4B用于datasizeof(size_t)字节用于指向data的指针和sizeof(size_t)用于文字指针 - 这是真的吗?

If the literal has static storage duration, no new memory is allocated for the local literal by the second call - is this true? 如果文字具有静态存储持续时间,则第二次调用不会为本地文字分配新内存 - 这是真的吗?

   char data[] = "aaa";

This is not a string literal but just an array. 不是字符串文字,而只是一个数组。 So there's no pointer there and memory is allocated only for the data . 所以那里没有指针,只为data分配内存。

If the literal has static storage duration, no new memory is allocated for the local literal by the second call 如果文字具有静态存储持续时间,则第二次调用不会为本地文字分配新内存

This is true for string literals like: char *s="aaa"; 这对于字符串文字是这样的: char *s="aaa"; From the standard: 从标准:

2.13. 2.13。 Sttring literals Sttring文字
[...]An ordinary string literal has type “array of n const char” and static storage duration (3.7) [...]普通的字符串文字具有类型“n const char数组”和静态存储持续时间(3.7)

There is no pointer variable here. 这里没有指针变量。 All there is an array, which is 4 bytes. 所有都有一个数组,这是4个字节。

The compiler may or may not store the literal itself in memory; 编译器可能会也可能不会将文字本身存储在内存中; if it does, that is another 4 bytes. 如果是,那就是另外4个字节。
Note that any memory taken up by anything other than the array itself is implementation-dependent. 请注意,除阵列本身以外的任何内存占用的任何内存都取决于实现。

I'm not sure what you mean by the "second call", but in general when you create an array, it takes up some amount of size... so if you create two arrays with the same literal, the compiler allocates space for two arrays (and perhaps -- or perhaps not -- for the literal also). 我不确定你的“第二次调用”是什么意思,但一般来说,当你创建一个数组时,它占用了一些大小...所以如果你创建两个具有相同文字的数组,编译器会为两个数组(也许 - 或许 - 或许不是 - 也为文字)。

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

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