简体   繁体   English

可以通过这种方式实现“struct hack”吗?

[英]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. Struck hack用于分配比结构本身初始需要更多的内存,以便您可以引用数组的越界部分,以便保留在实际分配的内存中。

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? 我们可以只使用一个整数而不是一个大小为1的数组吗? 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. 聪明的做法是使用std::vector ,这就是它的用途。 The struct hack is an old C-ism and redundant in C++. struct hack是一个旧的C-ism,在C ++中是多余的。

With the second version, you are unable to use the nice-looking direct array synatx. 对于第二个版本,您无法使用漂亮的直接阵列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]更短且更易读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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