P99
Macros
+ Collaboration diagram for Flexible array members:

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...
 

Detailed Description

C99 allows a flexible array member to be defined as the last member of a struct, namely an array of undetermined length.

P99_DECLARE_STRUCT(package_head);
struct package_head {
char name[20];
size_t len;
uint64_t data[];
};

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

package_head *a = malloc(sizeof(package_head) + 10 * sizeof(uint64_t));
package_head *b = malloc(sizeof(*b) + 12 * sizeof(b->data[0]));

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

offsetof(package_head, data) + N * sizeof(uint64_t)

so we are wasting

sizeof(package_head) - offsetof(package_head, data)

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

#define P99_FSIZEOF(T, F, N) P99_MAXOF(sizeof(T), offsetof(T, F) + P99_SIZEOF(T, F[0]) * N)

which is probably not something that you want to write on a daily basis.

We provide several interfaces to allocate struct with flexible members

See also
P99_FCALLOC
P99_FMALLOC
P99_FREALLOC
P99_DECLARE_STRUCT
#define P99_DECLARE_STRUCT(NAME)
forward declaration of a struct NAME
Definition: p99_type.h:59