Is it legal to implement inheritance in C by casting pointers between one struct that is a subset of another rather than first member?

Viewed 842

Now I know I can implement inheritance by casting the pointer to a struct to the type of the first member of this struct.

However, purely as a learning experience, I started wondering whether it is possible to implement inheritance in a slightly different way.

Is this code legal?

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

struct base
{
    double some;
    char space_for_subclasses[];
};

struct derived
{
    double some;
    int value;
};

int main(void) {
    struct base *b = malloc(sizeof(struct derived));
    b->some = 123.456;
    struct derived *d = (struct derived*)(b);
    d->value = 4;
    struct base *bb = (struct base*)(d);
    printf("%f\t%f\t%d\n", d->some, bb->some, d->value);
    return 0;
}

This code seems to produce desired results , but as we know this is far from proving it is not UB.

The reason I suspect that such a code might be legal is that I can not see any alignment issues that could arise here. But of course this is far from knowing no such issues arise and even if there are indeed no alignment issues the code might still be UB for any other reason.

2 Answers
Related