Pointers inside a shared memory segment

I tried this for hours, and google is all I am pleased with, but I'm losing my mind.

I have a structure:

typedef struct {
  int rows;
  int collumns;
  int* mat;
  char* IDs_row;
} mem;

I do not know the sizes of int * (matrix) and char * until a later time.

When I do this, I create shared memory as follows:

mem *ctrl;
int size = (2 + ((i-1)*num_cons))*sizeof(int) + i*26*sizeof(char); //I have the real size now
shmemid = shmget(KEY, size, IPC_CREAT | 0666);
if (shmemid < 0) {
    perror("Ha fallado la creacion de la memoria compartida.");
    exit(1);
}
ctrl = (mem *)shmat(shmemid, 0, 0);
if (ctrl <= (mem *)(0)) {
    perror("Ha fallado el acceso a memoria compartida");
    exit(2);
}

There are no problems. Then I give the value ctrl-> rows and columns and assign 0 to the whole matrix.

But after that I write something in char * and bam, segmentation fault.

Debugging the program, I saw that both pointers, mat and IDs_row, where null. How to provide them with the correct values ​​inside the shared memory segment?

I tried to remove the char * pointer to try, and then the segmentation failure error was in another program connected to the specified shared memory, and just checked the values ​​inside the matrix (checking → rows and → columns was successful)

+5
2
ctrl = (mem *)shmat(shmemid, 0, 0); 

ctrl, ctrl->mat ctrl->IDs_row.

, :

mem *ctrl;
shmemid = shmget(KEY, sizeof(ctrl), IPC_CREAT | 0666);
//allocate memory for the structure
ctrl = (mem *)shmat(shmemid, 0, 0);

//allocate memory for the int*
shmemid = shmget(KEY,((i-1)*num_cons))*sizeof(int), IPC_CREAT | 0666);
ctrl->mat = (int*)shmat(shmemid, 0, 0);

//allocate memory for the char*
shmemid = shmget(KEY,i*26*sizeof(char), IPC_CREAT | 0666);
ctrl->IDs_row = (char*)shmat(shmemid,0,0);
+5

, . , . . , , , shmaddr == NULL shmat(). shmat(), , , . . , , :

1) , mem, . , , .

2) , , , , shmget():

typedef struct {
  int rows;
  int collumns;
  int mat_id;
  int IDs_row_id;
} mem;

, , .

, KEY shmget() , KEY == IPC_PRIVATE. ( mem) IPC_PRIVATE , - , , .

+7

All Articles