title: Why am I getting a segfault (binary data parsing) c
body: <p>I'm scanning through raw bits 512 bytes at a time.  If the first 4 bytes match the jpeg file suffix I create a new jpeg and write that block and all following blocks to it, until I encounter a new jpeg suffix.</p>
  
  <p>For some reason it segfaults on the read call that follows the first write call.  </p>
  
  <p>/**
       * recover.c
       *
       * Computer Science 50
       * Problem Set 4
       *
       * Recovers JPEGs from a forensic image.
       */</p>
  
  <pre><code>#include &lt;stdint.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef uint8_t  BYTE;
  
  int main(int argc, char* argv[])
  {
      //load in file
      FILE* file = fopen("card.raw", "r");
      FILE* newfile = NULL;
  
      //error opening file
      if (file==NULL){
          return 1;
      }
  
      //create buffer and outfile index
      BYTE buffer[512]; //
      int filecount = 0;
      char newfilename[3];
  
      //iterate through file, break on eof
      while (1){//(!feof(file)){//(fgetc(file) != EOF){
  
          //seek back to 512 block start
          //fseek(file,-1,SEEK_CUR);
          //fread(&amp;buffer,1,512,file);
          if (fread(buffer,512,1,file) &lt;= 0){
              break;
          }
  
          //Check if first 4 bytes are jpeg signature
          if ((buffer[0] == 0xff &amp;&amp;
               buffer[1] == 0xd8 &amp;&amp;
               buffer[2] == 0xff &amp;&amp;
               buffer[3] == 0xe0)||
              (buffer[0] == 0xff &amp;&amp;
               buffer[1] == 0xd8 &amp;&amp;
               buffer[2] == 0xff &amp;&amp;
               buffer[3] == 0xe1 )){
  
              //close out previously created jpeg
              if (newfile != NULL){
                  //file close error
                  if (fclose(newfile) == EOF){
                      return 2;
                  }
                  newfile = NULL;
              }
  
              //create new jpeg
              sprintf(newfilename,"%03d.jpeg",filecount++);
              newfile = fopen(newfilename,"w");
  
          }
  
          //Write blocks to newfile
          if (newfile != NULL){
              if (fwrite(buffer,512,1,newfile) &lt;= 0){
                  return 4;
              }
  
          }
      }
  
      //close out last newfile 
      if (newfile != NULL){
          //file close error
          if (fclose(newfile) == EOF){
              return 3;
          }
          newfile = NULL;
      }
  
      //close infile
      fclose(file);
  
  
  
  //we should find 16 images
  
  
  }
  </code></pre>