c - 一般指针问题

标签 c pointers

为什么我可以增加指针来读取已分配变量的长度,并且操作系统不会阻止我?当然,既然它为整数留出了 4 个字节,它就应该知道它不应该允许任何指针超过这 4 个字节?

事实上,当我将指针递增到变量的已分配字节以上时,我到底在读取什么/那些相邻的内存位置是什么?由于每个程序都应该有自己的“地址空间”,所以我不能在该“地址空间”内做任何我想做的事情而不会出现段错误吗?如果每个程序都有自己的“地址空间”,那么应该不可能读取属于其他程序的内存,对吗?

最佳答案

我注意到这个问题是我昨天博客的主题。请参阅http://ericlippert.com/2014/05/07/why-does-my-code-not-crash

Why is it that I can increment pointers to read past the length of an allocated variable, and the OS doesn't stop me?

出于同样的原因,操作系统不会为您制作火腿三明治!没有人将火腿三明治功能写入操作系统,因此这种行为不会发生。未实现的功能未实现。您所使用的操作系统的功能并不能阻止您这样做。

Surely, since it was the one that set aside 4 bytes for an integer, it should know that it shouldn't allow any pointer to go past those 4 bytes?

不。操作系统通常会在称为页面的 4KB block 中预留地址空间

In fact, when I increment a pointer past the allocated bytes of a variable, what exactly am I reading? Are those adjacent memory locations?

是的。它们是相邻的虚拟内存位置。

since each program is supposed to have its own "address space", can't I do anything I want within that "address space" without a segfault?

没有。您可以在地址空间中对虚拟分配的地址执行任何操作。请注意,许多操作系统允许您对页面添加额外的约束,例如“此页面可以读取,但不能写入或执行”。在这些情况下,读取不会导致错误,但写入会导致错误。

It should be impossible to read memory that belongs to other programs if each program had its own "address space", right?

这并非不可能,但通常是故意的。在许多操作系统中,两个进程都可以同时将磁盘上文件的同一页映射到虚拟内存中,从而共享内存。

早在虚拟内存出现之前,Windows 3 等操作系统就允许两个进程毫无问题地互相写入内存,但现在几十年来情况并非如此。

关于c - 一般指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23553187/

相关文章:

c - 为什么在为 C 中的结构赋值时出现访问冲突

c - pthread_create() 调用线程指向的函数?

c - scanf 和指针的段错误

在指针上调用 delete 时发生 C++ 崩溃

c++ - 比较指针与 NULL 的编码标准

c++ - 指针函数

c - 在不同的 .c 文件中使用函数(c 编程 101)

c++ - 在 char* 中存储整数

c++ - 添加元素到列表会导致程序崩溃...有时

c++ - 当 vector 在内部类中时,如何删除指向对象的 vector 指针