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:
typedef struct {
float m;
float *x;
float *v;
float *f;
float R;
} *Particle;
typedef struct {
Particle *p;
int n;
float t;
} *ParticleSystem;
and here code for allocating
ParticleSystem sys = (ParticleSystem) malloc(sizeof(ParticleSystem));
sys->p = (Particle *) malloc(sizeof(Particle)*noOfParticles);
for(int i=0;i<noOfParticles;i++){
sys->p[i] = (Particle)malloc(sizeof(Particle));
sys->p[i]->f = (float*)malloc(sizeof(float)*2);
sys->p[i]->f[0] = 0.0f;
sys->p[i]->f[1] = 0.0f;
...
sys->p[i]->R = radius;
sys->p[i]->m = mass;
}
sys->n=noOfParticles;
sys->t = 0.0f;
and freeing
int n = sys->n;
for(int i=0;i<n;i++){
free(sys->p[i]->f);
...
free(sys->p[i]);//here it breaks
}
free(sys->p);
free(sys);
At line "free(sys->p[i]) it breaks. I don't know why, because first I do this
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."