Home > Mobile >  Is it okay to type-pun allocated structs varying only in const-ness?
Is it okay to type-pun allocated structs varying only in const-ness?

Time:11-23

In C (let's say C11 if we need to specific), is the following program well-defined? Will it always print a=3 b=4 or could compiler optimizations affect the output?

(The real-world motivation is to provide a read-only public "view" of a struct that is only supposed to be modified by a particular module, i.e. source file.)

#include <stdio.h>
#include <stdlib.h>

struct obj_private {
    int a;
    int b;
};

struct obj_public {
    const int a;
    const int b;
};

int main(void) {
    void *mem = calloc(1, sizeof(struct obj_private));
    struct obj_private *priv = mem;
    struct obj_public *pub = mem;

    priv->a = 3;
    priv->b = 4;

    printf("a=%d b=%d\n", pub->a, pub->b);

    return 0;
}

CodePudding user response:

These two types are not compatible. What you should be doing instead is using a pointer to a const object.

struct obj_private *priv = mem;
const struct obj_private *pub = mem;
  • Related