Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can "struct hack" be implemented this way?

Tags:

c++

struct

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;
like image 973
Eric Z Avatar asked Jul 24 '11 13:07

Eric Z


3 Answers

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++.

like image 55
Puppy Avatar answered Oct 23 '22 22:10

Puppy


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.

like image 25
marc Avatar answered Oct 23 '22 23:10

marc


Because it's more convenient to write p->data[i] than (&p->data)[i].

like image 5
Stan Avatar answered Oct 23 '22 21:10

Stan