views:

226

answers:

2

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.

+9  A: 

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
el.pescado
Ok, understood.
miguelSantirso
+1  A: 

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.

Nikolai N Fetissov