I'm creating a program in C that stores 3D objects and I'm trying to build some basic structs to form the building blocks of more complex objects. What I am doing is making create and destroy methods for each struct, so I can allocate and free memory cleanly in my other functions. The issue I am having is that in the higher levels of structs (the structs that contain the less complex structs), I want to free all of the structs within it when I run my delete method, but everything I am doing keeps giving me invalid pointer or double free errors. Here is a sample of what I am trying to do.
typedef struct Coordinate3D {
double x;
double y;
double z;
} Coordinate3D;
typedef struct Triangle3D {
Coordinate3D a;
Coordinate3D b;
Coordinate3D c;
} Triangle3D;
Coordinate3D* crd3D_create(double x, double y, double z)
{
Coordinate3D* result = malloc(sizeof(Coordinate3D));
result -> x = x;
result -> y = y;
result -> z = z;
return result;
}
void crd3D_destroy(Coordinate3D* c3D)
{
free(c3D);
}
Triangle3D* tri3D_create(Coordinate3D* a, Coordinate3D* b, Coordinate3D* c)
{
Triangle3D* result = malloc(sizeof(Triangle3D));
result -> a = *a;
result -> b = *b;
result -> c = *c;
return result;
}
void tri3D_destroy(Triangle3D* t3D)
{
/* This is where I run into problems, I want to do something like this but I
* do not know the correct syntax to get the address for these structs.
*/
crd3D_destroy(&(result->a));
crd3D_destroy(&(result->b));
crd3D_destroy(&(result->c));
free(t3D);
}
Thanks so much