小编Sam*_*Sam的帖子

为什么字符串文字根据声明为“char *”或“char[]”存储在不同的位置?

我对这个简单的事情进行了尴尬的斗争,因为这是段错误:

#include <stdio.h>

int main()
{
    char *test = "this is a string";
    test[0] = 'q';
    printf(test);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但这不是:

#include <stdio.h>

int main()
{
    char test[] = "this is a string";
    test[0] = 'q';
    printf(test);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

查看程序集后,我注意到在第一种情况下,文字"this is a string"是在 中声明的.rodata,因此这解释了段错误。但在第二种情况下,字符串根本不在程序集中,因此我假设它是通过 .data 部分链接为可写的。为什么会有这种行为差异?这很明显吗?我很愚蠢吗?

c assembly c-strings

1
推荐指数
1
解决办法
81
查看次数

标签 统计

assembly ×1

c ×1

c-strings ×1