P99
|
Macros | |
#define | P99_FCALLOC(T, F, N) calloc(P99_FSIZEOF(T, F, N),1) |
Allocate an instance of struct T that is able to hold N items in flexible struct member F. More... | |
#define | P99_FHEAD(T, F, P) ((T*)(((char*)P) - offsetof(T, F))) |
For a pointer P to a flexible struct member F in struct T find the start address of the container. More... | |
#define | P99_FMALLOC(T, F, N) malloc(P99_FSIZEOF(T, F, N)) |
Allocate an instance of struct T that is able to hold N items in flexible struct member F. More... | |
#define | P99_FREALLOC(P, T, F, N) realloc(P, P99_FSIZEOF(T, F, N)) |
Reallocate an instance P of struct T such that it is able to hold N items in flexible struct member F. More... | |
#define | P99_FSIZEOF(T, F, N) P99_MAXOF(sizeof(T), offsetof(T, F) + P99_SIZEOF(T, F[0]) * N) |
Compute the size for an instance of struct T that is able to hold N items in flexible struct member F. More... | |
C99 allows a flexible array member to be defined as the last member of a struct
, namely an array of undetermined length.
Such a struct
can then be allocated on the heap with a suitable size such that the field data
has as many elements as fit in the allocated space from the start of data
onward. Usually one would allocate such struct
with
This has several disadvantages. Firstly, the syntax is clumsy. We have to use a relatively complicated expression that uses two elements of the specification of a
or b
.
Secondly, it wastes space. Due to packing of the struct
the offset of data
"inside" the struct
may be less than sizeof(package_head)
. In most cases the real size of the object that we want to construct is
so we are wasting
bytes.
The above formula for the exact size is only valid for larger values of N
. We must also ensure that we allocate at least sizeof(package_head)
bytes. So the complete formula looks something like
which is probably not something that you want to write on a daily basis.
We provide several interfaces to allocate struct
with flexible members