我对这个简单的事情进行了尴尬的斗争,因为这是段错误:
#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 部分链接为可写的。为什么会有这种行为差异?这很明显吗?我很愚蠢吗?