将在何处进行C中字符串的内存分配

时间:2021-07-13 22:25:36

For the C statement given below i would like to know where the memmory allocation will take place.

对于下面给出的C语句,我想知道memmory分配将在何处进行。

char* ptr="Hello";//ptr is a automatic variable

then the pointer variable ptr will be allocated on the stack,but where will this string "Hello" be allocated. Is it on Stack or on Heap? And what about memory allocation for initialization statement like char ptr[]="Hello";

那么指针变量ptr将在堆栈上分配,但是这个字符串“Hello”将在哪里被分配。它是在堆栈上还是在堆上?那么初始化语句的内存分配如char ptr [] =“Hello”;

2 个解决方案

#1


12  

The standard doesn't say (it doesn't know about "stack", "heap" etc). But in practice the answer is: Neither. The string literal will be stored in the data section, usually in a read-only page.

标准没有说(它不知道“堆栈”,“堆”等)。但实际上答案是:两者都没有。字符串文字将存储在数据部分中,通常位于只读页面中。

As a side note, as Als mentions in the comments, it's undefined behavior to attempt to modify a string literal.

作为附注,正如Als在评论中提到的那样,尝试修改字符串文字是未定义的行为。

#2


3  

With static strings like in your example, the string is not really allocated. Space for it is made in the executable itself, and the above assignment just sets "ptr" to the address of that space.

对于示例中的静态字符串,字符串并未真正分配。它的空间是在可执行文件本身中创建的,上面的赋值只是将“ptr”设置为该空间的地址。

I'm not sure if this is implementation dependent or not, but the string is usually in protected memory so you cannot change it ... only point to it.

我不确定这是否依赖于实现,但字符串通常位于受保护的内存中,因此您无法更改它...仅指向它。

In UNIX, you can see the static strings in an executable by using the "strings" command on an executable.

在UNIX中,您可以通过在可执行文件上使用“strings”命令来查看可执行文件中的静态字符串。

#1


12  

The standard doesn't say (it doesn't know about "stack", "heap" etc). But in practice the answer is: Neither. The string literal will be stored in the data section, usually in a read-only page.

标准没有说(它不知道“堆栈”,“堆”等)。但实际上答案是:两者都没有。字符串文字将存储在数据部分中,通常位于只读页面中。

As a side note, as Als mentions in the comments, it's undefined behavior to attempt to modify a string literal.

作为附注,正如Als在评论中提到的那样,尝试修改字符串文字是未定义的行为。

#2


3  

With static strings like in your example, the string is not really allocated. Space for it is made in the executable itself, and the above assignment just sets "ptr" to the address of that space.

对于示例中的静态字符串,字符串并未真正分配。它的空间是在可执行文件本身中创建的,上面的赋值只是将“ptr”设置为该空间的地址。

I'm not sure if this is implementation dependent or not, but the string is usually in protected memory so you cannot change it ... only point to it.

我不确定这是否依赖于实现,但字符串通常位于受保护的内存中,因此您无法更改它...仅指向它。

In UNIX, you can see the static strings in an executable by using the "strings" command on an executable.

在UNIX中,您可以通过在可执行文件上使用“strings”命令来查看可执行文件中的静态字符串。