为什么这个小 C 程序会崩溃?
程序是:
#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';
,当我删除它时,程序工作正常。但我无法弄清楚原因。
The program is:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a="abc",*ptr;
ptr=a;
ptr++;
*ptr='k';
printf("%c",*ptr);
return 0;
}
The problem is in the
*ptr='k';
line, when I remove it program works normally. But I can't figure out the reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是因为您试图将字符串文字
"abc"
更改为:这是未定义的行为。该标准明确规定,根据 C99 的
6.4.5 字符串文字
部分,您不允许更改字符串文字:它就会起作用
如果将:替换为:,
,因为这会将字符串文字复制到可以安全修改的位置。
The problem is because you are trying to change the string literal
"abc"
with: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 will work if you replace:
with:
since that copies the string literal to a place that's safe to modify.
因为“abc”是一个常量字符串文字。然后你将
ptr
指向它并尝试修改它,这是未定义的行为。通常,字符串文字被放入一个内存部分,该部分被映射为只读 - 因此出现访问冲突。另请参阅此问题:字符串文字:它们去了哪里?
Because "abc" is a constant string literal. Then you point
ptr
to it and try to modify it which is undefined behaviour. Typically string literals are put in a memory section which gets mapped as read-only - hence the access violation.See also this question: String literals: Where do they go?
原因是您的字符串
"abc"
位于内存的只读区域。它由链接器放置在那里。你试图在你的程序中改变它,但一切都失败了。The reason is that your string
"abc"
lives in a read-only area of memory. It gets put there by the linker. You try to change it in your program, and all bets are off.这:
确实是:
您无法修改
ptr
,它指向与a
相同的地址。This:
is really:
You can't modify
ptr
, which points to the same address asa
.