为什么写一个字符串在这个C程序段错误的文字? [英] Why does writing to a string literal in this C program segfault?
本文介绍了为什么写一个字符串在这个C程序段错误的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include<stdio.h>
void main()
{
char *p="nyks";
p[2]='n';
printf("%s",p);
}
这崩溃了分段错误即可。有人能解释为什么吗?
This crashes with a SEGMENTATION FAULT. Can someone explain why?
推荐答案
标准决定了文字字符串定义常量
。你不能改变它。
The standard dictates that literal strings are defined const
. You cannot change it.
编译器将文字在只读存储器部分。您可以输出装配和观察这一点。如果你正在使用GCC则是通过-s标志完成。这将会把字符串中.RODATA部分。
The compiler places the literal in a readonly memory section. You can output the assembly and observe this. If you are using GCC it is done via the -s flag. It will place the string in a .rodata section.
这篇关于为什么写一个字符串在这个C程序段错误的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文