title: Delete shared memory linux with ipcrm
body: <p>I am writing a simple application on C that uses shared memory but I cannot run it anymore as it says:</p>
  
  <p><code>shmat: Cannot allocate memory</code></p>
  
  <p>I am using <a href="https://stackoverflow.com/a/4262545/2587048">this</a> script to free my memory but doesn't seem to work.</p>
  
  <p>This is a screenshot of my processes:</p>
  
  <p><a href="https://i.stack.imgur.com/0nbTL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0nbTL.png" alt="enter image description here"></a></p>
  
  <p>This is the application code:</p>
  
  <pre><code>/* Shared Memory IPC creates a mamory space and send contendt to it while the other process can read from it.
  Our implementation works like this:
      1. First run the application by passing as a argument the value you want to send to the shared memory. Example: ./ipc_sharedmem.o 4
      2. Run the appliation again to read from the shared memory (which is a new process, of course) wihout sending any arguments. Exmaple: ./ipc_sharedmem.o
  */
  
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/ipc.h&gt;
  #include &lt;sys/shm.h&gt;
  
  #define SHM_SIZE 1024  /* make it a 1K shared memory segment */
  
  int main(int argc, char *argv[])
  {
      key_t key;
      int shared_mem_mid;
      char *data;
  
      struct timeval t1, t2, t3, t4;
  
      if (argc &gt; 2) {
          fprintf(stderr, "usage: shmdemo [data_to_write]\n");
          exit(1);
      }
  
      /* make the key: */
      if ((key = ftok("mach.c", 'R')) == -1) {
          perror("ftok");
          exit(1);
      }
  
      /* connect to (and possibly create) the segment: */
      if ((shared_mem_mid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
          perror("shmget");
          exit(1);
      }
  
      /* attach to the segment to get a pointer to it: */
      gettimeofday(&amp;t1, NULL);
      data = (char *) shmat(shared_mem_mid, (void *)0, 0);
      gettimeofday(&amp;t2, NULL);
      if (data == (char *)(-1)) {
          perror("shmat");
          exit(1);
      }
  
      printf("Time to read the message from sharem memory: %g \n", (t2.tv_sec + t2.tv_usec/1000000.0)-(t1.tv_sec + t1.tv_usec/1000000.0));
  
      /* read or modify the segment, based on the command line: */
      if (argc == 2) {
          printf("writing to segment: \"%s\"\n", argv[1]);
          gettimeofday(&amp;t3, NULL);
          strncpy(data, argv[1], SHM_SIZE);
          gettimeofday(&amp;t4, NULL);
          printf("Time to send data to shared memory: %g \n", (t4.tv_sec + t4.tv_usec/1000000.0)-(t3.tv_sec + t3.tv_usec/1000000.0));
      } else{
  
          printf("segment contains: \"%s\"\n", data);
      }
      /* detach from the segment: */
      if (shmdt(data) == -1) {
          perror("shmdt");
          exit(1);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Any idea?</p>