Reputation: 597
I try to use shmget with a 2D array. This is my code :
char **array;
key_t key;
int size;
int shm_id;
int i = 0;
void *addr;
key = // here I get the key with ftok()
size = (21 * sizeof(char *)) + (21 * sizeof(char **));
shm_id = // here I get the shmid with shmget()
if (shm_id == -1) // Creation
{
array = (char **)shmat(shm_id, NULL, SHM_R | SHM_W);
while (i != 20)
{
array[i] = memset(array[i], ' ', 20);
array[i][20] = '\0';
i++;
}
array[i] = NULL;
shm_id = // here I get the shmid with the flag IPC_CREAT to create the shared memory
addr = shmat(shm_id, NULL, SHM_R | SHM_W);
}
But I've a segmentation fault with the line "array[i] = memset(array[i], ' ', 20);"
What am I doing wrong?
Upvotes: 1
Views: 826
Reputation: 121407
You should first check whether shmget succeeds or not. if allocation of shared memory fails, then you can't be using shared memory! ;-) Like:
If ( shm_id = shmget(.......) == -1) {
exit(1);
}
else {
/* proceed with your work*/
}
and the same for shmat as well.
shmget returns void*. you can't assign it to a char** and and use it like a 2d array. In fact, a char* can easily be handled as a 2D array logically.
Upvotes: 2