title: CS50 pset4 recover segmentation fault
body: <p>When I compile and run my program, I get a segmentation fault. Valgrind doesn't show any problems. Any thoughts?
  I'm going crazy trying to figure out the problem.</p>
  <p>The point of the program is to recover JPEGS from a &quot;forensic image&quot; called card.raw .  When I run check50 on the code the program fails to meet the requirements due to a seg fault.</p>
  <p>This is my code:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  
  int main(int argc, char *argv[])
  {
  int jpeg_count = 0;
  
  if(argc != 2)
  {
      printf(&quot;Usage: ./recover image\n&quot;);
      return(1);
  }
  
  FILE *original;
  original = fopen(argv[1], &quot;r&quot;);
  
  if(original == NULL)
  {
      printf(&quot;Error! Cannot open file.\n&quot;);
      return(1);
  }
  
  unsigned char buffer[512];
  char *filename = malloc(8);
  fread(buffer, sizeof(buffer), 512, original);
  
  FILE *img; 
  
  while(1)
  {
      if(buffer[0] == 0xff &amp;&amp; buffer[1] == 0xd8 &amp;&amp; buffer[2] == 0xff &amp;&amp; (buffer[3] &amp;0xf0) == 0xe0)
      {
          if(jpeg_count == 0)
          {
              sprintf(filename, &quot;%03i.jpg&quot;, 0);
              img = fopen(filename, &quot;w&quot;);
              fwrite(buffer, sizeof(buffer), 512, img);
              jpeg_count++;
          }
          else if(jpeg_count &gt; 0)
          {
              fclose(img);
              sprintf(filename, &quot;%03i.jpg&quot;, jpeg_count);
              img = fopen(filename, &quot;w&quot;);
              fwrite(buffer, sizeof(buffer), 512, img);
              jpeg_count++;
          }
      
      }
      if(feof(original))
      {
          fclose(img);
          fclose(original);
          free(filename);
          break;
              
      }             
  }
  
  }
  </code></pre>