Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers inside shared memory segment

I've been trying this for hours, and google all the things I kind think of, but I'm going crazy.

I have a struct:

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

I don't know the sizes of the int* (a Matrix) and char* untill later.

When I do, I create the shared memory like this:

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);
}

No problem here. Then I give a value to ctrl->rows and collumns, and assign 0 to all the matrix.

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

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

I tried removing the char* pointer, just to give it a try, and then the segmentation fault error was in the other program that connected to said shared memory and just checked the values inside the matrix (checking ->rows and ->collumns was succesfull)

like image 879
Knudow Avatar asked May 27 '12 19:05

Knudow


1 Answers

ctrl = (mem *)shmat(shmemid, 0, 0); 

This only assigns valid memory to the ctrl pointer, not to ctrl->mat or ctrl->IDs_row.

You probably want:

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);
like image 93
Luchian Grigore Avatar answered Sep 29 '22 05:09

Luchian Grigore