【问题标题】:how is memory allocated when a character pointer points to a string?当字符指针指向字符串时如何分配内存?
【发布时间】:2011-12-03 04:41:09
【问题描述】:
#include<stdio.h>

int main(void)
{
    /* in this amessage is an array big enough to
     * hold  the sequence of character and '\0' */
    char amessage[] = "now is the time";

    /* in this case a character pointer is
     * pointing to a string constant */
    char *pmessage = "now is the time";

    return 0;
}

我很困惑在第二种情况下如何分配内存?那个内存副本是私有的吗……我的意思是写一些东西作为 2nd stmt 是否安全,并确保其他任何东西都不会覆盖相同的内存??

【问题讨论】:

  • 不,你不能确定。你应该通过你的编程来照顾自己
  • @Mr.DDD:你确定吗?我认为大多数编译器会将这些数据加载到进程内存的不同段中,而不是堆中。
  • @Mr.DDD - 不会有任何加载(复制)。它很可能会指向可执行文件数据部分中的某个位置
  • 使用带有默认优化选项的microsoft c,字符串数据本身被分配在静态数据段中。在这两种情况下,堆栈上都没有分配任何内容。指向数据段的指针在寄存器中分配。任何一个字符串都是可变的。

标签: c string memory pointers memory-management


【解决方案1】:
char *pmessage = "now is the time";

创建一个字符串文字,该字符串的内存分配在只读位置的某个位置,具体取决于编译器的实现细节。

修改它会导致未定义的行为。因此,如果您使用的是字符串文字,您有责任确保不要尝试写入该只读存储器。

【讨论】:

  • 字符串文字的空间不必来自只读位置:在系统上存在 C 的实现,对于这些实现来说,谈论只读位置是没有意义的。
  • @pmg:答案是:it is implementation dependent detail of compilers to be specific.
  • 对...我的意思是它不必是只读位置。该实现可以为字符串文字“选择”良好的旧读/写内存。
【解决方案2】:

字符串字面量可以不同:这是编译器的选择(C99 Standard 表示未指定)。

假设一下,更改字符串文字本身不是 UB。

int main(void) {
    char *p = "now is the time";
    /* compiler makes sure there is a place with "now is the time"
    ** and makes p point there */
    char *q = "time";
    /* possibly, the compiler reuses the time from
    ** the previous string literal */

    q[0] = 'd'; /* technically UB: don't do this */
    puts(p);    /* possibly writes "now is the dime" */
}

针对您的具体问题:只要您不调用 UB,它就是安全的。编译器分配的内存考虑了所有其他对象的所有其他用途。

【讨论】:

    【解决方案3】:

    很安全。它们将被分配在堆栈上。 message 和 pmessage 的唯一区别是 pmessage 是只读的。

    【讨论】:

    • 编译器实际上应该警告或拒绝这个。字符串文字是只读的,因此不应将它们分配给非常量指针。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2020-03-23
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多