cunions

Do pointers to different types match the "common initial sequence" rule?


If I have a union that contains pointers to different types of data, would it be legal to free malloced memory via a different field than the one it was assigned to? Does it even match the "common initial sequence" rule?

#include <stdlib.h>

typedef struct {
    int type;
    union {
        void *entries;
        long *long_entries;
        // etc
    } u;
} Bar;

int main (void) {
   Bar bar;
   bar.u.long_entries = malloc(6 * sizeof(long));
   free(bar.u.entries);
}

I'm inclined to say that this is legal, but I'm not entirely sure.


Considering the answers so far, I think I would have to change my code to something like this; which I expect is fully legal:

typedef struct {
    int type;
    void *entries;
} Bar;

int main(int argc, char *argv[]) {
    Bar bar;
    bar.entries = malloc(6 * sizeof(long));
    // ...
    long *long_entries = bar.entries;
    long_entries[3] = 123;
    // ...
    free(bar.entries);
}

Solution

  • If I have a union that contains pointers to different types of data, would it be legal to free malloced memory via a different field than the one it was assigned to? Does it even match the "common initial sequence" rule?