Home > Net >  Directly make pointer from ints
Directly make pointer from ints

Time:03-04

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?

CodePudding user response:

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.

  • Related