title: Pointer becomes nothing for no apparent reason
body: <p>Greetings!</p>
  
  <p>I have a simple program in qt on c.
  There are two pointers to type short, used to read from file and store bits from values read.</p>
  
  <p>sample code:</p>
  
  <pre><code>//(input is a FILE* which is opened and passed to the function)
  //(output is also a FILE* which is also opened and passed to the function)
  
  //1. Variables declaration
  short* sample_buffer;
  int buffer_size=1;
  short samples_read;
  unsigned long value_x=7;
  short* nzb_buffer;
  short buffer_position=-1;
  int i;
  
  //2.Memory allocation
  sample_buffer= malloc(sizeof(short)*buffer_size);
  nzb_buffer = malloc(sizeof(short)*value_x);
  
  ....
  
  //3. Read from infile, one short at time, process and write it to outfile
  do
  {
       //3.1. Read from input file
       samples_read = fread(sample_buffer,sizeof(short),buffer_size, input);
       //3.2. Switch position inside nzb_buffer one to the right, 
       //     going back to zero if out of bounds
       buffer_position=(buffer_position+1)%value_x;
  
       ....
  
       //3.3. Put least significant bit of the just read short into nzb_buffer
       nzb_buffer[buffer_position]=sample_buffer[0]%2;
  
       ....
  
       //3.4. Write the short we just read from infile to the outfile
       for (i=0;i&lt;samples_read;i++)
       {
           fwrite(sample_buffer,sizeof(short),1, output);
       }
  } while(samples_read==buffer_size);
  </code></pre>
  
  <p>I've let unreliant pieces of code out. If you need to see something else please tell me.</p>
  
  <p>Problem is, after like 10 or 15 operations of the loop, it crashes with "Segmentation fault" signal. It crashes on the fwrite() function.</p>
  
  <p>I debugged and i use watch on sample_buffer. For some reason, on one exact step, the operation nzb_buffer[buffer_position]=sample_buffer[0]%2 makes sample_buffer become 0x0 (i belive, it becomes a null pointer). </p>
  
  <p>This cannot be overflowing on nzb_buffer because buffer_position for that operation is 3 (out of 7 allocated for the particular array in malloc). And since each loop makes one write operation and shifts the carry, the operation of writing into nzb_buffer[3] has already happened before in the loop and did not nullify the pointer that time.</p>
  
  <p>I am totally clueless what may be happening here. 
  Anybody has any ideas what is going on or how do i debug it?</p>
  
  <p>Thanks in advance!</p>
  
  <p>PS: Added comments "what the code does"</p>