C中如何实现只读内存? [英] How is read-only memory implemented in C?

查看:29
本文介绍了C中如何实现只读内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C 中听说过,如果我这样做了

I heard that in C, if I do

char *s = "hello world". 

hello world"实际上存储在只读内存中.

the "hello world" is actually stored in read-only memory.

我对只读内存不是很清楚.解释是什么?这是否像是编译器的一个标志,告诉编译器不要写入该部分?

I am not so clear about read-only memory. What is the explanation? Is that like a flag to the compiler that tells the compiler to do not write into that section?

推荐答案

这不是 C 语言 但是编译器/链接器和操作系统协同工作的一个特性.

That's not a feature of the C language but a feature of the compiler/linker and the operating system working together.

当您编译此类代码时,会发生以下情况:

When you compile such code the following happens:

  • 编译器会将字符串放入只读数据段.

  • The compiler will put the string into a read-only data-section.

链接器收集此类只读段中的所有数据并将它们放入单个段中.该段驻留在可执行文件中,并带有只读"属性标记.

The linker collects all the data in such read-only sections and puts them into a single segment. This segment resides in the executable file and is flagged with a "read only"-attribute.

现在是操作系统可执行加载器.它加载可执行文件(或更准确地将其映射到内存中).完成此操作后,加载程序会遍历各个部分并为每个部分设置访问权限.对于只读数据段,它很可能会禁用代码执行和写访问.代码(例如,您的函数)获得执行权限但没有写访问权限.像静态变量这样的普通数据获得读写访问权限等等...

Now comes the operating system executable loader. It loads the executable (or maps it into memory to be more exact). Once this is done, the loader walks the sections and sets access-permissions for each segment. For a read-only data segment it will most likely disable code-execute and write access. Code (for example, your functions) gets execute rights but no write access. Ordinary data like static variables gets read and write access and so on...

现代操作系统就是这样做的.

That's how modern operating systems do it.

如前所述,这不是 C 语言的特性.例如,如果您为 DOS 编译相同的问题,程序将运行但不可能有写保护,因为 DOS 加载程序不知道只读部分.

As said, it's not a feature of the C language. If you compile the same problem for DOS, for example, the program will run but no write protection would be possible, because the DOS-loader does not know about read-only sections.

这篇关于C中如何实现只读内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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