title: Reading data from file into a struct (C)
body: <p>Sorry if this formatting is messy this is my first time using stackoverflow. 
  I am trying to use the <code>fread</code> function to read into the <code>card.raw</code> file in blocks of 512 bytes and store the first 4 bytes of the block into <code>s1-s4</code> and the other 508 bytes left over into the array of bytes. However, when I try to run this I get a segmentation fault. When I tried debugging, after the <code>fread</code> function is called, <code>argv</code>, <code>outptr</code>, <code>inptr</code>, and <code>buf</code> values all become <code>NULL</code>. Why is that and what am I doing wrong?</p>
  
  <pre><code>typedef uint8_t  BYTE;
  
  //block of 512 bytes
  typedef struct 
  {
      BYTE s1;
      BYTE s2;
      BYTE s3;
      BYTE s4;
      BYTE image[508];
  }
  BUFFER;
  
  int main(int argc, char* argv[])
  {
      //opens memory card file
      FILE* inptr = fopen("card.raw", "r");
  
      int jpgcounter = 0;
  
      //creates jpg file
      char title[7];
      sprintf(title, "%d.jpg", jpgcounter);
      FILE* outptr = fopen(title, "a");
  
      //create buf (pointer) of type BUFFER
      BUFFER* buf;
  
      do
      {
          //creates buffer structure for storage of 512B blocks 
          buf = malloc(sizeof(BUFFER));
  
          //read 512 bytes at a time &amp; stores every 512B block into a buffer struct buf
          fread(&amp;buf, sizeof(BUFFER), 1, inptr);
  
          if(buf-&gt;s1 == 0xff &amp;&amp; buf-&gt;s2 == 0xd8 &amp;&amp; buf-&gt;s3 == 0xff)
          {
  </code></pre>
  
  <p>The if statement is used to check if the first 3 elements of <code>buf</code> contain the following hexadecimal signatures. I wanted to use <code>malloc</code> in a loop in order to read the raw file in structs of 512 bytes, decide what to do with the 512 bytes, then free it continuously. </p>