Hatefiend Hatefiend - 2 months ago 12x
C Question

C - Struct Constructor and Deconstructor

If I have a struct like:

struct Cell
unsigned int *x, *y;
char flag;

Would the following constructor and deconstructors be sufficient for safely allocating and de-allocating memory?

// Constructor function.
struct Cell *Cell_new()
struct Cell *born = malloc(sizeof(struct Cell));
if (born == NULL)
return NULL;
born->x = NULL;
born->y = NULL;
born->flag = false;
return born;

// Deconstructor function.
// When called, use Cell_destroy(&cell);
char Cell_destroy(struct Cell **cell)
cell = NULL;

Is this correct?

One thing I don't understand is if I do:

struct Cell *myCell = Cell_new();

When I'm calling
, it is expecting an address to a pointer (a pointer to a pointer) and yet I'm providing an address to a struct.

What I mean is

My function expects:

Pointer -> Pointer -> Tangible Object

What I'm giving it:

Pointer -> Tangible Object

Is this flawed logic? I've been looking up this for awhile so it's safe to say I might be confusing myself.


It is correct to pass a parameter of type struct Cell ** to the destructor function because, this function will change the value of the pointer intended.

So, if you want to free the object and set the pointer to NULL, you can write:

void Cell_destroy(struct Cell **cell)
    *cell = NULL;

Note how cell is de-referenced.