直接从 int 生成指针

发布于 2025-01-11 21:53:59 字数 611 浏览 3 评论 0原文

我正在学习共享内存,我想将指向结构变量的地址从一个进程发送到另一个进程。

我所做的是将变量的地址写入共享内存,打印地址,然后通过无限循环使进程保持活动状态。这个进程将被称为进程1。代码:

    ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
    sprintf(ptr, "%p", &temp);

之后,我从另一个进程(进程2)读取地址作为char数组,然后我将其转换为long int,用这段代码

    sscanf((char*) ptr, "%lx", &intVal);

然后我直接分配一个指针具有此值的结构:

    student* p = intVal;

但是当我尝试访问内存区域时,它会产生分段错误,尽管当我运行此行时,

    printf("variable A is at address: %p\n", p);

它会打印进程 1 的确切地址。

那么为什么即使我保持两个进程都处于活动状态,C 也会给出分段错误?

I was learning about shared memory, and I would like to send an address pointed to a struct variable from one process to another.

What I did was writing the variable's address into the shared memory, printing the address, then keeping the process alive with an infinite loop. This process will be called process 1. The code:

    ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
    sprintf(ptr, "%p", &temp);

After that, I read the address as a char array from another process (process 2), then I casted it to a long int, with this code

    sscanf((char*) ptr, "%lx", &intVal);

then I directly assign a pointer of said struct with this value:

    student* p = intVal;

but when I try to access the memory region, it produces a Segmentation Fault, although when I run this line

    printf("variable A is at address: %p\n", p);

it prints the exact address from process 1.

So why does C give segmentation error even when I keep both processes alive?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

战皆罪 2025-01-18 21:53:59

欢迎来到虚拟内存,其中每个进程都有自己的地址空间。

一个进程中一个地址上的内容与另一进程中同一地址上的内容完全无关。这意味着一个进程不能有意或无意地写入另一进程使用的内存。阅读也是如此。

这对于稳定性很有好处。一个行为不当的程序不会使整个机器崩溃。这也允许不同的用户拥有不同的权限。

Welcome to virtual memory, where each process has its own address space.

What's located at one address in one process is completely unrelated to what's located at the same address in a different process. This means one process can't intentionally and accidentally write to memory used by another process. And same goes for reading.

This is great for stability. One misbehaving program doesn't crash the entire machine. This also permits different users with different permissions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文