简体   繁体   中英

Pointer in structure memory allocation in initialization (c99)

Lets assume that we've got a type:

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

Is it correct allocating memory next way in c99?

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

Compiler shows warning

Variable 'data' is uninitialized when used within its own initialization

Memory's available and all, but are there some other non-warning options to do the same?

From 6.7.9p23:

The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another [...] (152) In particular, the evaluation order need not be the same as the order of subobject initialization.

So there is no guarantee that a.size is initialized at the point calloc(a.size, 1) is evaluated for the initialization of a.buf .

In this case, a suitable initializer would be a creation function:

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 can't be used for static or file-scope objects; in that case a macro would be necessary (or, for example, a gcc statement expression, which could be used in a macro).

The structure is not fully initialized until after the assignment of a , because you don't 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 have to do it in separate steps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM