为什么这个小的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'.
这是不确定的行为。该标准明确规定,您不得修改字符串为每节 6.4.5字符串字面
的C99:
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.
它的将会的工作,如果你替换:
It will work if you replace:
char *a="abc",*ptr;
与
char a[]="abc",*ptr;
因为这复制字符串到可以安全地修改的地方。
since that copies the string literal to a place that's safe to modify.
这篇关于为什么这个小的C程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!