title: Why am I getting a segmentation fault with this code?
body: <p>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.)</p>
  My code:
  <pre><code>   #include&lt;stdlib.h&gt;
     #include&lt;sys/types.h&gt;
     #include&lt;sys/shm.h&gt;
     #include&lt;sys/ipc.h&gt;
     #include&lt;stdio.h&gt;
     #include&lt;sys/sem.h&gt;
  
     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(&quot;/home/mawia/abc.c&quot;,'a');
  
    printf(&quot;entered into main of producer\n&quot;);
    if(semkey&lt;0)
    {
     perror(&quot;ftok&quot;);
     exit(1);
    }
  
    shmid=shmget(semkey,30,0777);
  
    if(shmid&lt;0)
    {
     printf(&quot;error&quot;);
     perror(&quot;shmget&quot;);
     exit(1);
    }
  
    shm=shmat(shmid,0,0);
    if(shm==(char *) -1)
    {
    perror(&quot;shm&quot;);
    exit(1);
    } 
  
    s=shm;
    semid=semget(semkey,1,0777);
   if(semid&lt;0)
   {
    printf(&quot;error&quot;);
    perror(&quot;semget&quot;);
    exit(0);
   }
  
   ptrr=shm+1;
   *s='w';
   printf(&quot;going to check the value 0th semaphores\n&quot;);
   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(&quot;entered the critical region\n&quot;);
   //printf(&quot;waiting to enter the buffer zone...&quot;);
   semop(semid,buf,2);
  
   printf(&quot;entered the critical region\v&quot;);
   if(*s!='r')
   {
    printf(&quot;\nPRODUCER IS PRODUCING\n\n\n&quot;);
  
    printf(&quot;ENTER DATA\n&quot;);
  
    while((c=getchar())!='\n')
    {
      *ptrr++=c;
    }
    *ptrr='\0';
    *s='r';
   } 
  
    else 
    printf(&quot;RESOURCE IS FULL:CAN'T PRODUCE&quot;);
  
   //printf(&quot;produced enough for  the consumer \nexiting from the buffer area now...&quot;);
   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,&quot;exit&quot;))
    {
    printf(&quot;exiting...&quot;);
    exit(0);
    }
    sleep(1);
  
   return 0;
    }
  </code></pre>