title: CS50 Recover - memory issue
body: <p>I'm a bit stymied by this problem, so I'd love any advice or insight into what I'm doing wrong.</p>
  <p>In short, when submitting the below Recover code to CS50's CHECK50, I pass every test except the last one. Instead, I get this error in the CHECK50 terminal:</p>
  <pre><code>checking that program exited with status 0...checking for valgrind errors...
  472 bytes in 1 blocks are still reachable in loss record 1 of 1: (file: recover.c, line: 28)
  </code></pre>
  <p>That error seems straightforward to me. I'm allocating something in memory that I'm not freeing by the end of the code. Here's the operation at line 28 that that the error readout is pointing to:</p>
  <pre><code>FILE *mem_card = fopen(argv[1], &quot;r&quot;);
  </code></pre>
  <p>From that, I thought all I would have to do is is <code>free(mem_card);</code> at the end of recover.c. However, doing that gave me a <em>huge</em> amount of new Valgrind errors. So I'm a bit stuck and not sure how to approach this, as I don't know what I'm doing wrong.</p>
  <p>I've removed the comments from my recover.c code and included it here for more context:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdint.h&gt;
  
  typedef uint8_t BYTE;
  
  int main(int argc, char *argv[])
  {
      int BLOCK_SIZE = 512;
      int jpeg_count = 0;
      BYTE buffer[BLOCK_SIZE];
  
      FILE *img;
  
      if (argc != 2)
      {
          printf(&quot;Usage: ./recover IMAGE\n&quot;);
          return 1;
      }
  
      FILE *mem_card = fopen(argv[1], &quot;r&quot;); // CHECK50/Valgrind issue here
      if (mem_card == NULL)
      {
          printf(&quot;Could not open for reading %s.\n&quot;, argv[1]);
          return 1;
      }
  
      char filename[8] = {};
  
      while (fread(buffer, 1, BLOCK_SIZE, mem_card) == BLOCK_SIZE)
      {
          if (buffer[0] == 0xff &amp;&amp; buffer[1] == 0xd8 &amp;&amp; buffer[2] == 0xff &amp;&amp; (buffer[3] &amp; 0xf0) == 0xe0)
          {
  
              sprintf(filename, &quot;%03i.jpg&quot;, jpeg_count);
  
              if (jpeg_count == 0)
              {
                  jpeg_count++;
  
                  img = fopen(filename, &quot;w&quot;);
                  fwrite(buffer, 1, BLOCK_SIZE, img);
              }
              else if (jpeg_count &gt; 0)
              {
                  jpeg_count++;
  
                  fclose(img);
                  img = fopen(filename, &quot;w&quot;);
                  fwrite(buffer, 1, BLOCK_SIZE, img);
              }
          }
          else if (jpeg_count &gt; 0)
          {
              fwrite(buffer, 1, BLOCK_SIZE, img);
  
          }
          else
          {
  
          }
      }
      fclose(img);
      //free(mem_card);
      return 0;
  }
  </code></pre>