In this Stackoverflow question or in the article Undefined behavior can result in time travel (among other things, but time travel is the funkiest) one may learn that accessing data structures at indexes greater than their size is undefined behavior, and when a compiler sees undefined behavior, it generates crazy code without even reporting that undefined behavior was encountered. This is done to make code run a few nanoseconds faster and because the standard permits it. So-called "time travel" appears because the compiler operates on control-flow branches, and when it sees undefined behavior in a branch, it just deletes that branch (on the basis that any behavior will do in place of undefined behavior).
Nevertheless, here is an old idiom:
struct myString {
int length;
char text[1];
}
used as
char* s = "hello, world";
int len = strlen(s);
myString* m = malloc(sizeof(myString) + len);
m->length = len;
strcpy(&m->text,s);
and now, what will happen if I access m->text[3]
? (Note how it is declared.) Will the compiler take it as undefined behavior? If yes, how do I add an array of statically unknown amount of items to the end of a structure?
In particular, I am interested in an array whose size is at least 1, but maybe more. Sort of,
struct x {
unsigned u[1];
};
and access like `struct x* p; ... p->x[3]`.
UPD related: Is the "struct hack" technically undefined behavior? (as @mafso has noted in a comment).