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."
It's been a while since I've done C/C++ programming, but don't those typedefs declare Particle to be of type pointer-to-that-struct and ParticleSystem to be of type pointer-to-that-other-struct? If so, when you allocate the memory you're only allocating enough memory to hold a pointer, not the actual struct.
For example:
#include <iostream>
using namespace std;
typedef struct {
float m;
float *x;
float *v;
float *f;
float R;
} *Particle;
typedef struct {
Particle *p;
int n;
float t;
} *ParticleSystem;
int main()
{
cout << "sizeof(Particle) = " << sizeof(Particle) << endl;
cout << "sizeof(ParticleSystem) = " << sizeof(ParticleSystem) << endl;
return 0;
}
and when I run that program I get:
sizeof(Particle) = 4
sizeof(ParticleSystem) = 4
I would not use an asterisk when making such a typedef. This easily leads to a lot of confusion when malloc'ing memory and using pointers. Just use
typedef struct {
float m;
float *x;
float *v;
float *f;
float R;
} Particle;
This will make it much more clear, I don't even know which behaviour your typedef causes (your probably only alloc space for a pointer)
Just take a line at those 2 lines:
sys->p = (Particle *) malloc(sizeof(Particle)*noOfParticles);
sys->p[i] = (Particle)malloc(sizeof(Particle));
I assume you want to get memory for the pointers in the first place and than memory for the struct itself in the second. But how should this work? You use sizeof(Particle) in both mallocs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With