的char *分配分割故障 [英] Segmentation fault of char * assignment

查看:91
本文介绍了的char *分配分割故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是想了解字符分割故障*期间下面的程序分配在位置* P ='Z'

I was trying to understand segmentation fault for char * assignment during for the following program for at location *p = 'Z'

void main()
{
   char *p ="abcdefg";
   *p = 'Z';
}

在GOOGLE上搜索,我发现很多链接的答案如下
1.这是一个字符串文字,分配一次不能有它的价值变化
2.字符串字面量不能被分配​​到* P
3.取可changd一个malloc ...等等...

When Googled, i did find many links to answers as follows 1. This is a string literal and once assigned cannot have its value changed 2. String literals cannot be assigned to *p 3. Take a malloc which can be changd... and so on...

但我担心的是,如果字符串值不能被改变,因为它是恒定的,怎么来的,当我们换一个整数恒定值,我们不分段错误。
是否有人可以帮助我更好的理解?

But my worry was if string literals values can't be changed as it is constant, how come we don't segmentation fault when we change constant value of a integer. Can someone please help me understand this better?

-Prashanth

-Prashanth

推荐答案

这是未定义的行为。如果你有一个常量字符串,标准说,字符串可能不被修改。所以还判定是否它是可写的或不依赖于体系结构,它可以或可以不出现段错误。

It's undefined behaviour. If you have a constant string, the Standard says that string literals may not be modified. So wether it is writable or not depends on the architecture, and it may, or may not segfault.

更新的评论说。

这篇关于的char *分配分割故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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