I recently came across some code that uses a "cool hack" like the following:
#include <stddef.h>
#include <stdlib.h>
struct foo {
int a;
char *b;
int optional;
char huge[5000];
/* lots more members */
};
void myfunc(void) {
struct foo *p;
p = malloc(offsetof(struct foo, optional));
if (p) {
p->a = 17;
p->b = "Hello";
/* do stuff with p->a and p->b */
free(p);
}
}
The idea is to "save memory" by only allocating the part of struct foo
that is actually going to be used.
I see many obvious reasons why this code is a bad idea: it will certainly break if you reorder the members of struct foo
, or if you forget which members you're allowed to use, or if you accidentally assign *p
or pass it to a function by value. (And in the code linked, it saves a whopping 80 bytes per call, for a function that most programs will only call a handful of times.)
But is it actually undefined behavior or otherwise illegal with respect to the C standard? If so, are there examples of real-life implementations where it won't work as intended?