在 C++ 中读取内存时出现分段错误

Segmentation fault while reading Memory in C++

我只是想使用两个 C++ 代码获取存储在特定内存地址的值

我用来将数据写入内存并获取其地址的代码:

#include <iostream>

using namespace std;

int main()
{
  int i = 10;
  cout<<&i<<endl;
  cin>>i; // This is just to make sure program doesn`t end

  return 0;
}

我使用 cin>>i; 只是为了确保它不会结束。 得到int i的地址后,输入以下代码:

#include <iostream>

using namespace std;

int main()
{
  // This address changes everytime and I change it everytime
  // This is just one temporary address
  volatile int *x = (volatile int *)0x7ffef9246e74; // [1]
  int y = *x;
  cout<<y<<endl;

  return 0;
}

[1] :我从 this page.

复制了这一行

程序 #1 保持 运行ning 而我 运行 程序 #2

在 运行 宁第二个代码,我得到 segmentation fault (core dumped)。有帮助吗?

您关于现代操作系统、编译器等工作方式的模型是错误的。当您第一次 运行 程序时,进程会被分配一个内存 space。此内存 space 中的所有内容都是 虚拟 内存 space,由处理器的 MMU 映射到 物理 内存.

当进程结束时,它的内存 space 不再存在。下次启动同一个程序时,它会 运行 在另一个独立的内存 space 中。它可能映射到不同的物理内存地址,甚至虚拟地址也不相同,或者它们被清除以确保没有信息从以前的进程中泄漏。

这意味着当您将第一个程序的地址输入到第二个程序时,它在那里没有任何意义。更糟糕的是,第一个 运行 的内存地址不是第二个 运行 的虚拟内存 space 的一部分,因此 CPU MMU 检测到对内存位置的非法访问,您会遇到段错误。