title: Can't deallocate pointer to structure previously allocated
body: <p>I'm creating easy particle system. I've got two typedef structures. First represents single particle with some fields. Second represents system of particles. My problem is that I can't deallocate memory allocated for each Particle. Really don't know what's wrong.
  Here are structures:</p>
  
  <pre><code>typedef struct {
     float m;  
     float *x;  
     float *v;    
     float *f;     
     float R;
  } *Particle;
  
  typedef struct {
     Particle *p;
     int n; 
     float t; 
  } *ParticleSystem;
  </code></pre>
  
  <p>and here code for allocating </p>
  
  <pre><code>ParticleSystem sys = (ParticleSystem) malloc(sizeof(ParticleSystem));  
  sys-&gt;p =  (Particle *) malloc(sizeof(Particle)*noOfParticles);
  
  for(int i=0;i&lt;noOfParticles;i++){
      sys-&gt;p[i] = (Particle)malloc(sizeof(Particle));
  
      sys-&gt;p[i]-&gt;f = (float*)malloc(sizeof(float)*2);
      sys-&gt;p[i]-&gt;f[0] = 0.0f;
      sys-&gt;p[i]-&gt;f[1] = 0.0f;
  
      ...
  
      sys-&gt;p[i]-&gt;R = radius;
      sys-&gt;p[i]-&gt;m = mass;
  
  }
  
  sys-&gt;n=noOfParticles;
  sys-&gt;t = 0.0f;
  </code></pre>
  
  <p>and freeing  </p>
  
  <pre><code>int n = sys-&gt;n;
  for(int i=0;i&lt;n;i++){
      free(sys-&gt;p[i]-&gt;f);
  
      ...
  
      free(sys-&gt;p[i]);//here it breaks
  }
  free(sys-&gt;p);
  free(sys);
  </code></pre>
  
  <p>At line "free(sys->p[i]) it breaks. I don't know why, because first I do this<br>
    sys->p[i] = (Particle)malloc(sizeof(Particle)) to allocate. Visual Studio says "HEAP[template.exe]: Invalid address specified to RtlValidateHeap( 01E70000, 01E749B0 )
  Windows has triggered a breakpoint in template.exe."</p>