为什么修改字符串导致段错误? [英] Why does modifying a string literal cause a segmentation fault?

查看:108
本文介绍了为什么修改字符串导致段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么修改pre-初始化字符串导致段错误?例如:

Why does modifying a pre-initialized string literal cause a segmentation fault? For example:

char *str = "Hello world";
str[0] = 'h'; 

在初始化 STR 来的字符串值,不会对编译器自动分配内存为字符串常量,指定其起始位置海峡和自由它在程序退出?

When you initialize str to that string value, doesn't the compiler automatically allocate memory for that string constant, assign its starting location to str and free it upon program exit?

推荐答案

这是在进程的地址空间的只读部分,因为字符串是一个常数。 (在 STR 变量不是只读空间,但它提出,要指向一个有效的可写位置,然后才能使用它,你做的方式。)

it is in a read only section of the process's address space because the string literal is a constant. (the str variable is not in read only space but it should be made to point to a valid writable location before you can use it the way you do.)

这篇关于为什么修改字符串导致段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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