Hatefiend Hatefiend - 1 year ago 152
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download