title: How to access variables in shared memory
body: <p>I am trying to create a shared memory segment containing three integers and an array. The segment is created and a pointer is attached, but when I try to access the values of the variables (whether changing, printing, etc.) I get a segmentation fault.</p>
  
  <p>Here is the code I tried:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdbool.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/ipc.h&gt;
  #include &lt;sys/sem.h&gt;
  #include &lt;sys/shm.h&gt;
  
  #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;
  }
  </code></pre>
  
  <p>I tried accessing the shared memory by dereferencing the pointer to the struct, but got a segmentation fault each time.</p>
  
  <p>Thanks everyone, no segmentation faults now.</p>