[英]possible reason of crash of following code?
I tested the following code on two different compilers, it crashed on first but worked fine on second? 我在两个不同的编译器上测试了以下代码,该代码第一次崩溃,但第二次运行良好?
The code is 该代码是
char *str="testing";
*str='b';
printf("%c",*str);
b
on second compiler b
在第二个编译器上 What may be the possible reason of crash? 崩溃的可能原因是什么?
The reason for the crash is that writing into a string literal's memory is undefined behavior. 崩溃的原因是写入字符串文字的内存是未定义的行为。 Your code
*str='b'
writes directly into the first char
of memory allocated to the string literal. 您的代码
*str='b'
直接写入分配给字符串文字的内存的第一个char
。 C allows compilers to place the content of literals into the memory area that is protected from writing. C允许编译器将文字内容放入防止写操作的存储区中。 Writing anywhere in that region causes a segmentation fault.
在该区域的任何地方写入都会导致分段错误。
Change the declaration to 将声明更改为
char str[]="testing";
to avoid the error. 避免错误。 If you declare
str
as a char
array (as opposed to a char
pointer) the compiler generates code to copy the content of str
into writable memory, thus avoiding the error when you write to str
. 如果将
str
声明为char
数组(与char
指针相对),则编译器将生成代码以将str
的内容复制到可写内存中,从而避免在写入str
时出错。
您正在写入字符串文字,这具有未定义的行为。
通常(和您所看到的一样,取决于系统),字符串文字会被放入只读内存中,然后尝试对其进行更改将导致运行时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.