miguelSantirso
miguelSantirso

Reputation: 1253

Is it possible to allocate a 2D array as shared memory with IPC?

I want to allocate shared memory as a 2D array using IPC. I tried the following:

id_shmem = shmget(ipc_key, sizeof(int)*rows*columns, IPC_CREAT|0666);

matrix = (int **)shmat(id_shmem, 0, 0);

The problem is that whenever I try to write something into the matrix, I get a segment fault.

Upvotes: 3

Views: 3202

Answers (2)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

Common practice with structures in shared memory is storing offsets and not pointers. This is to get around the fact that memory could be mapped at different virtual addresses in different processes.

Another common approach is to let first process request OS-provided mapping and then somehow pass the resulting virtual address to all other processes that need to be attached to the same memory, and have them request fixed mapping at that address.

Upvotes: 3

int** is not 2D array, it is rather an array of pointers. You should not store pointers in shared memory, as shared memory segment may be allocated at different addresses in different processes. Try to use simple, flat 1D array, which will "emulate" 2D array with some index magic, ie.

x,y -> y*width+x

Upvotes: 14

Related Questions