简体   繁体   中英

Can “struct hack” be implemented this way?

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.

因为写p->data[i](&p->data)[i]更方便。

因为p->data[i](&p->data)[i]更短且更易读。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM