I'm doing an university project and I was asked to create a kind of game between processes: they have to capture some flags placed over a shared matrix, similar to a chessboard. I represented the board using a struct and cells as a matrix but, after allocating the shared memory segment, I cannot attach it correctly because when I try to access to matrix cells I get "segmentation fault", in fact I see that matrix pointer is zero. So, how do I attach the matrix after the whole board is allocated?
Here's the code of the functions I wrote to allocate/attach the board:
int allocate_board(int width, int height){
size_t size;
int shm_id;
key_t shm_key;
char current_path[PATH_MAX];
getcwd(current_path, sizeof(current_path));
shm_key = ftok(current_path, 1);
size = sizeof(board) + ( sizeof(cell) * height * width );
shm_id = shmget(shm_key, size, IPC_CREAT | 0660);
if ( shm_id < 0 ){
printf("Cannot allocate the game board, aborting.\n");
exit(1);
}
return shm_id;
}
board* get_board(int shm_id){
void* shm_ptr;
board* game_board;
shm_ptr = shmat(shm_id, NULL, 0);
if ( (int)shm_ptr == -1 ){
printf("Cannot attach the shared memory segment, aborting.\n");
printf("Reported error: %s.\n", strerror(errno));
exit(2);
}
game_board = (board *)shm_ptr;
return game_board;
}
Here's the structs definition:
typedef struct {
entity_type_t entity_type;
owner_id_t owner_id;
float flag_score;
} cell;
typedef struct {
int width;
int height;
sem_t* semaphore;
cell** cells;
} board;
Here's how I try to access to board's cells:
game_board->width = some_width;
game_board->height = some_height;
game_board->cells[0][0].flag_score = some_score;