Struck hack is used to allocate more memory than the initial need of the struct itself so that you can reference the out-of-bounds part of the array such that you stay inside the memory actually allocated.
Here's how it works.
struct Foo
{
// ..
size_t size;
int data[1];
};
const size_t SIZE = 100;
Foo *p = (Foo*) malloc(sizeof(Foo) + sizeof(int) * (SIZE - 1));
p->size = SIZE;
for (int i = 0; i < p->size; ++i) (p->data)[i] = i;
Question:
Can we just use a single integer instead of an array of size one? If that's doable, why does the array-of-size-one version become much more popular then?
struct Foo
{
// ..
size_t size;
int data;
};
// ..
for (int i = 0; i < p->size; ++i) (&p->data)[i] = i;