为什么此代码会产生分段错误?
在第18行,我在第一次迭代中得到一个seg错误(i = 0)。
#include int main(void) { char* str = "mono"; int length = 0; int i; for (i = 0; ; i++) { if (str[i] == '\0') { break; } else { length++; } } for (i = 0; i < length / 2; i++) { char temp = str[length - i - 1]; str[length - i - 1] = str[i]; // line 18 str[i] = temp; } printf("%s", str); return 0; }
我写了这个算法来反转一个字符串。
您正在修改字符串文字:
char* str = "mono";
和字符串文字在C中是不可修改的。
要解决您的问题,请使用由字符串文字初始化的数组:
char str[] = "mono";
运行时错误:
char* str = "mono"; // str points to an address in the code-section, which is a Read-Only section str[1] = 'x'; // Illegal memory access violation
编译错误:
const char* str = "mono"; // This is a correct declaration, which will prevent the runtime error above str[1] = 'x'; // The compiler will not allow this
都好:
char str[] = "mono"; // str points to an address in the stack or the data-section, which are both Read-Write sections str[1] = 'x'; // Works OK
笔记:
-
在所有情况下,字符串“mono”都放在程序的代码部分中。
-
在最后一个示例中,该字符串的内容被复制到
str
数组中。 -
在最后一个示例中,如果
str
是非静态局部变量,则str
数组位于堆栈中,否则位于程序的数据部分中。