'Directly make pointer from ints

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source