我正在尝试创建一个包含三个整数和一个数组的共享内存段。该段已创建并附加了一个指针,但是当我尝试访问变量的值(无论是更改、打印等)时,我遇到了分段错误。
这是我尝试过的代码:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#define SIZE 10
int* shm_front;
int* shm_end;
int* shm_count;
int* shm_array;
int shm_size = 3*sizeof(int) + sizeof(int[SIZE]);
int main(int argc, char* argsv[])
{
int shmid;
//create shared memory segment
if((shmid = shmget(IPC_PRIVATE, shm_size, 0644)) == -1)
{
printf("error in shmget");
exit(1);
}
//obtain the pointer to the segment
if((shm_front = (int*)shmat(shmid, (void *)0, 0)) == (void *)-1)
{
printf("error in shmat");
exit(1);
}
//move down the segment to set the other pointers
shm_end = shm_front + 1;
shm_count = shm_front + 2;
shm_array = shm_front + 3;
//tests on shm
*shm_end = 10; //gives segmentation fault
printf("\n%d", *shm_end); //gives segmentation fault
//clean-up
//get rid of shared memory
shmdt(shm_front);
shmctl(shmid, IPC_RMID, NULL);
printf("\n\n");
return 0;
}
我尝试通过取消引用指向结构的指针来访问共享内存,但每次都出现分段错误。
谢谢大家,现在没有分段错误。