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

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

问题描述

我听说在C,如果我做

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 operation system working together.

在编译这样code会发生以下情况:

When you compile such code the following happens:


  • 编译器将会把字符串放到只读数据段。

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

链接器收集在这种只读节中的所有数据,并将它们放入一个段。这部分驻留在可执行文件被标记了只读-attribute。

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.

现在自带操作系统的可执行文件加载器。它加载的可执行文件(或它映射到内存中更准确)。一旦这样做,加载器遍历节并设置的访问权限,对每个段。对于只读数据段,将最有可能禁用code-执行和写入权限。 code(例如,你的函数)得到执行的权利,但没有写权限。像静态变量普通数据被读取和写入权限等等...

Now comes the operation 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 now modern operation 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天全站免登陆