0

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

Nick5741
  • 11
  • 2
  • 4
    You cannot free parts of an allocated block. Those structs are directly embedded into the allocated memory area of the enclosing struct. You don't allocate memory with extra `malloc` calls and hence cannot free anything except the whole struct. – Gerhardh Apr 13 '22 at 10:38
  • More duplicates: https://stackoverflow.com/questions/58820329/free-a-part-of-malloc https://stackoverflow.com/questions/49775436/free-first-part-of-dynamic-memory-in-c https://stackoverflow.com/questions/62340279/how-to-free-a-part-of-contiguous-allocated-memory-in-c – Gerhardh Apr 13 '22 at 10:46

0 Answers0