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;
Accessing an array outside of it's bounds is undefined behaviour. For example, your debugger might decide to insert canary arrays each side of the array.
The smart thing to do would be to just use a std::vector
, that's what it's for. The struct hack is an old C-ism and redundant in C++.
With the second version, you are unable to use the nice-looking direct array synatx. You can't do
p->data[i]
anymore but have to do
(&p->data)[i]
what looks much more ugly.
Because it's more convenient to write p->data[i]
than (&p->data)[i]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With