...
A small collection of macros can provide secure implementations for common uses for the standard memory allocation functions.
Code Block | ||
---|---|---|
| ||
/* allocates a single object using malloc(). */ #define MALLOC(type) ((type *)malloc(sizeof(type))) /* allocates an aarray singleof objectobjects using {{malloc()}}. */ #define MALLOC_ARRAY(number, type) \ ((type *)malloc(number * sizeof(type))) /* allocates an a single object with a flexible array of objectsmember using {{malloc()}}. */ #define MALLOC_FLEX(stype, number, etype) \ ((stype *)malloc(sizeof(stype) + number * sizeof(etype))) /* allocates aan singlearray object with a flexible array memberof objects using {{malloccalloc()}}. */ #define CALLOC(number, type) \ ((type *)calloc(number, sizeof(type))) allocates/* reallocates an array of objects using {{callocrealloc()}}. */ #define REALLOC_ARRAY(pointer, number, type) \ ((type *)realloc(pointer, number * sizeof(type))) /* reallocates ana single object with a flexible array of objectsmember using realloc()}}. */ #define REALLOC_FLEX(pointer, stype, number, etype) \ ((stype *)realloc(pointer, sizeof(stype) + number * sizeof(etype))) reallocates a single object with a flexible array member using {{realloc()}}. |
For example,
Code Block | ||
---|---|---|
| ||
enum month { Jan, Feb, ... }; type enum month month; typedef enum date date; struct date { unsigned char dd; month mm; unsigned yy; }; typedef struct string string; struct string { size_t length; char text[]; }; date *d, *week, *fortnight; string *name; d = MALLOC(date); week = MALLOC_ARRAY(7, date); name = MALLOC_FLEX(string, 16, char); fortnight = CALLOC(14, date); |
...