cshared-memorysysv-ipc

What stops me from reading/writing further than the size of a shared memory? (System V IPC)


What I'm doing is:

shmget(shm_key, shm_size, 0666 | IPC_CREAT); (and of course attach to it)

and I've already set the size to exactly 12 Bytes but when i try something like:

sprintf(shm_ptr, "Imagine about 200-300 characters here\n");

it seems to work normally with zero problems or warnings, and to check that, I tried to read it from a completely different process (i fork and exec the first one) and sure enough

printf("%s", shm_ptr);

prints the message that was in that segment, which is supposed to be 12 Bytes. Is System V IPC supposed to be like this, and there is no workaround for that issue? If so, why set a size in the first place?

Thanks for your time and answers in advance.


Solution

  • Nothing stops you, but the spec does not guarantee any specific behavior for this case.

    In practice, the actual size of a memory region will be round up to a system-specific page size. This makes it possible to access more memory than was requested, but there might be consequences. For example, memory sanitizers might treat this as an error.

    This is true for all memory mapping, including those created with mmap.

    Now, why do you need to access memory beyond requested region? If you need more memory, just request more. Having memory sanitizers not going crazy due to unexpected behavior is a very useful thing. Other than that, I don't think there are any consequences to this, at least I cannot come up with anything atm.

    EDIT: If you want to find access errors in your code, you can put a single "guard page" at the end of your memory block. Just allocate one additional page of memory and use mprotect to change its access rights to PROT_NONE. This way you will get segfault if you go beyond your mapping (but no more than 1 page).