指针和字符串分割造成的故障 [英] Pointers and Strings causing segmentation fault

查看:128
本文介绍了指针和字符串分割造成的故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/9460260/what-is-the-difference-between-char-a-string-and-char-p-string\">What为char之间的差的[] =&ldquo;串rdquo ;;和char * p =&ldquo;串rdquo ;;


 的char *海峡=你好;
的printf(%C,++ * STR);

这给出了与海湾合作委员会的Linux分段错误。
当下的第一个语句修改为

 字符海峡[10] =你好;

它的工作原理。可能是什么原因呢?


解决方案

这是不确定的行为试图修改字符串。

编译器可以自由地将其放置在只读存储器(因为它可能是你的情况一样)。试图修改只读存储器是什么可能触发段错误。

Possible Duplicate:
What is the difference between char a[] = “string”; and char *p = “string”;

char *str = "Hello";
printf("%c",++*str);

This gives segmentation fault on linux with gcc. The moment the first statement is changes to as

char str[10] = "Hello";

It works. What may be the reason?

解决方案

It is undefined behaviour to attempt to modify a string literal.

The compiler is free to place it in read-only memory (as it probably does in your case). Attempting to modify read-only memory is what's probably triggering the segfault.

这篇关于指针和字符串分割造成的故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆