title: C - Bus error when using mmap
body: <p>I am trying to write a program that uses the <code>mmap</code> function in C to read a file, map the contents of the file to memory, and (for now) output the first character in the file. I have written the code below, and all is well up until the last line, where I attempt to print the character. At that point, the program outputs <code>Bus error (core dumped)</code>.</p>
  
  <p>What could be going wrong with this program? I followed <a href="http://beej.us/guide/bgipc/output/html/multipage/mmap.html" rel="nofollow">this tutorial</a> and I don't appear to have done anything that would lead to it not working. For reference, the file I am reading in contains one line: "The quick brown fox jumped over the lazy dog". I want to make sure my program is correct before working on additional functionality, so I would expect the output to be the first character, "T".</p>
  
  <pre><code>/* open file */
  file = open(fileName, O_RDONLY);
  
  /* check if file exists */
  if (file == -1) {
      printf("File not found\n");
      return 1;
  }
  
  /* get page size */
  pageSize = getpagesize();
  
  /* map file to memory */
  data = mmap((caddr_t)0, pageSize, PROT_READ, MAP_SHARED, file, pageSize);
  
  /* check if map was successful */
  if (data == (caddr_t)(-1)) {
      printf("mmap error\n");
      return 1;
  }
  
  printf("%c\n", data[0]);
  </code></pre>