Pointer in the allocation of structure memory during initialization (c99)

Suppose we have a type:

typedef struct __BUFF_T__ { u_int8_t *buf; u_int32_t size; }buff_t; 

Is it correct to allocate memory as follows in c99?

 buff_t a = {.size = 20,.buf = calloc(a.size,1)}; 

The compiler shows a warning

Variables "data" are not initialized when used as part of their own initialization

There is memory available and that’s all, but are there other options without warning to do the same?

+4
source share
2 answers

From 6.7.9p23:

The estimates of the initialization list expressions are vaguely ordered using each other [...] (152) In particular, the evaluation order should not be the same as the order of initialization of a subobject.

Thus, there is no guarantee that a.size initialized at the point calloc(a.size, 1) is evaluated to initialize a.buf .

In this case, the creation function is a suitable initializer:

 inline buff_t create_buff(u_int32_t size) { return (buff_t) {.size = size, .buf = calloc(size, 1)}; } buff_t a = create_buff(20); 

This cannot be used for objects in a static or file area; in this case, you need a macro (or, for example, an expression of the gcc operator, which can be used in a macro).

+4
source

The structure is not fully initialized until the value a is assigned, because you do not know in which order the expressions will be evaluated.

If you need to use a structure field to initialize another field in the same structure, you must do this in separate steps.

+3
source

All Articles