c - Memory allocation for structure extension -
suppose have 2 structures 1 of extends other 1 (as below). what's correct procedure dealing memory when creating extended structure existing structure? should malloc called again new structure? doubling memory allocation shouldn't be?
typedef struct grid { int rows; int cols; int * grid; } grid; typedef struct supergrid { grid; char * property; int id; } supergrid; static grid * new_grid(int rows, int cols) { grid * grid = (grid *)(malloc(sizeof(grid))); grid->rows= rows; grid->cols= cols; grid->grid = (int *)(calloc(rows*cols, sizeof(int))); } static supergrid * new_super_grid(int rows, int cols) { /* needs happen here? */ return (supergrid *)new_grid(rows, cols); }
your structure extension mechanism similar primitive c++ class derivation system. achieve goal, need separate structure allocation , initialization:
typedef struct grid { int rows; int cols; int *grid; } grid; typedef struct supergrid { grid; char *property; int id; } supergrid; static grid *init_grid(grid *grid, int rows, int cols) { if (grid) { grid->rows = rows; grid->cols = cols; grid->grid = (int *)calloc(rows * cols, sizeof(int)); } return grid; } static grid *new_grid(int rows, int cols) { return init_grid((grid *)malloc(sizeof(grid)), rows, cols); } static supergrid *init_super_grid(supergrid *sg, int rows, int cols, const char *property, int id) { if (sg) { init_grid((grid *)sg, rows, cols); sg->property = strdup(property); sg->id = id; } return sg; } static supergrid *new_super_grid(supergrid *sg, int rows, int cols, const char *property, int id) { return init_super_grid((supergrid *)malloc(sizeof(supergrid)), rows, cols, property, id); }
the allocators may fail , return null
in case of memory allocation failure. may want them fail in more explicit ways such exiting program error message via abort
. similarly, delete_xxx
functions should gracefully ignore null
pointers free
, c++ delete
operator.
for consistency, separate delete_grid
, finalize_grid
functions in order call finalize_grid
finalize_super_grid
. not strictly necessary simple example, may prove handy if instantiate grid
structures not allocated (with static or automatic storage or embedded in more complex superstructures).
this poor man's c++ class system show limitations. may consider using c++ directly.
Comments
Post a Comment