静态C字符串分配问题 [英] Static C string allocation question

查看:115
本文介绍了静态C字符串分配问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

char* str = "Hello World";
memcpy(str, "Copy\0", 5);

在memcpy的过程中出现分段错误。但是,使用此code:

A segmentation fault occurs during the memcpy. However, using this code:

char str[12];
memcpy(str, "Hello World\0", 12);
memcpy(str, "Copy\0", 5);

该程序不会产生分段错误。

The program does not produce a segmentation fault.

问题是否从堆栈与数据部分的分配内存出现?

Does the problem arise from allocating the memory on the stack versus the data section?

推荐答案

当你使用一个字符串字面GCC的价值被放置在只读存储器,不能修改。试图修改它会导致不确定的行为。通常当你尝试这样做,你将获得在Linux分割故障。

When you use a string literal in gcc the value is placed in read-only memory and cannot be modified. Trying to modify it leads to undefined behaviour. Usually you will get a segmentation fault on Linux when you try to do this.

第二个例子的作品,因为你没有修改字符串,您正在修改存储在变量的副本是不是只读的。

The second example works because you aren't modifying the string literal, you are modifying a copy of it that is stored in variable that is not read-only.

这篇关于静态C字符串分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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