为什么这个小 C 程序会崩溃? [英] Why does this small C program crash?
问题描述
程序是:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a="abc",*ptr;
ptr=a;
ptr++;
*ptr='k';
printf("%c",*ptr);
return 0;
}
问题出在
*ptr='k';
行,当我删除它时,程序正常工作.但我无法弄清楚原因.
line, when I remove it program works normally. But I can't figure out the reason.
推荐答案
问题是因为您试图将字符串文字 "abc"
更改为:
The problem is because you are trying to change the string literal "abc"
with:
char *a="abc",*ptr;
ptr=a; // ptr points to the 'a'.
ptr++; // now it points to the 'b'.
*ptr='k'; // now you try to change the 'b' to a 'k'.
这是未定义的行为.该标准明确规定,您不得根据 C99 的 6.4.5 String literals
节更改字符串文字:
That's undefined behaviour. The standard explicitly states that you are not permitted to change string literals as per section 6.4.5 String literals
of C99:
如果这些数组的元素具有适当的值,则不确定这些数组是否不同.如果程序试图修改这样的数组,则行为未定义.
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
如果你替换它会工作:
char *a="abc",*ptr;
与:
char a[]="abc",*ptr;
因为这会将字符串文字复制到可以安全修改的地方.
since that copies the string literal to a place that's safe to modify.
这篇关于为什么这个小 C 程序会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!