How to initialize const in a struct in C (with malloc)

You need to cast away the const to initialize the fields of a malloc’ed structure:

struct deneme *mydeneme = malloc(sizeof(struct deneme));
*(int *)&mydeneme->a = 15;
*(int *)&mydeneme->b = 20;

Alternately, you can create an initialized version of the struct and memcpy it:

struct deneme deneme_init = { 15, 20 };
struct deneme *mydeneme = malloc(sizeof(struct deneme));
memcpy(mydeneme, &deneme_init, sizeof(struct deneme));

You can make deneme_init static and/or global if you do this a lot (so it only needs to be built once).


Explanation of why this code is not undefined behaviour as suggested by some of the comments, using C11 standard references:

  • This code does not violate 6.7.3/6 because the space returned by malloc is not “an object defined with a const-qualified type”. The expression mydeneme->a is not an object, it is an expression. Although it has const-qualified type, it denotes an object which was not defined with a const-qualified type (in fact, not defined with any type at all).

  • The strict aliasing rule is never violated by writing into space allocated by malloc, because the effective type (6.5/6) is updated by each write.

(The strict aliasing rule can be violated by reading from space allocated by malloc however).

In Chris’s code samples, the first one sets the effective type of the integer values to int, and the second one sets the effective type to const int, however in both cases going on to read those values through *mydeneme is correct because the strict-aliasing rule (6.5/7 bullet 2) permits reading an object through an expression which is equally or more qualified than the effective type of the object. Since the expression mydeneme->a has type const int, it can be used to read objects of effective type int and const int.

Leave a Comment