I want to share an array in shared memory but i can't fill it cause give me back segmentation fault and i have no idea why.This is the first time with shared memory so i don't know how to use it for my purpose.
int main(int argc, char const *argv[])
{
int *array;
int shmid;
shmid = shmget(1234,3*sizeof(int),IPC_CREAT);
if(shmid == -1) {
perror("shmget error");
exit(EXIT_FAILURE);
}
array = (int*)shmat(shmid,NULL,0);
int array_copy[3];
int i;
for (i = 0; i < 3; i ){
array_copy[i] = i;
memcpy( &array[i], &array_copy[i], sizeof(int) );
}
for (i = 0; i < 3; i )
printf("\n nm: %d and array: %d",array_copy[i],array[i]);
shmdt((void *) array);
return 0;
}
CodePudding user response:
You're not checking the result of shmat()
. On my system it fails and perror()
says "Permission denied". So you can look for answers here: c programming shmat ( ) permission denied