I am getting a segmentation fault while running this code. I can’t work out why this is happening – can anyone see a possible reason? (I have already got and initialized the semaphore’s shared memory.)
My code:
#include<stdlib.h> #include<sys/types.h> #include<sys/shm.h> #include<sys/ipc.h> #include<stdio.h> #include<sys/sem.h> union semun { int val; struct semid_ds *buf; unsigned short *array; } arg; int main() { key_t semkey; int shmid,semid,nsem,sops; struct sembuf buf[1]; char *ptrr,*shm,c,*s; semkey=ftok("/home/mawia/abc.c",'a'); printf("entered into main of producer\n"); if(semkey<0) { perror("ftok"); exit(1); } shmid=shmget(semkey,30,0777); if(shmid<0) { printf("error"); perror("shmget"); exit(1); } shm=shmat(shmid,0,0); if(shm==(char *) -1) { perror("shm"); exit(1); } s=shm; semid=semget(semkey,1,0777); if(semid<0) { printf("error"); perror("semget"); exit(0); } ptrr=shm+1; *s='w'; printf("going to check the value 0th semaphores\n"); buf[0].sem_num=0; buf[0].sem_op=0; buf[0].sem_flg=0; buf[1].sem_num=0; buf[1].sem_op=1; buf[1].sem_flg=0; printf("entered the critical region\n"); //printf("waiting to enter the buffer zone..."); semop(semid,buf,2); printf("entered the critical region\v"); if(*s!='r') { printf("\nPRODUCER IS PRODUCING\n\n\n"); printf("ENTER DATA\n"); while((c=getchar())!='\n') { *ptrr++=c; } *ptrr='\0'; *s='r'; } else printf("RESOURCE IS FULL:CAN'T PRODUCE"); //printf("produced enough for the consumer \nexiting from the buffer area now..."); buf[0].sem_num=0; buf[0].sem_op=-1; buf[0].sem_flg=0; semop(semid,buf,1); ptrr=shm+1; if(!strcmp(ptrr,"exit")) { printf("exiting..."); exit(0); } sleep(1); return 0; }
After a quick glance (very quick), i would say that it MAY be caused by
You are accessing memory outside of the buffer. buf[1] reserves memory in the stack for only one struct sembuf, you are trying to use 2. In that case, you should use