Can so-called "structural hacks" be implemented?

Struck hack is used to allocate more memory than the initial need of the structure itself, so you can reference the part outside the array so that you stay inside the actually allocated memory.

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:

Is it possible to use only one integer, and not an array of size one? If feasible, why will a version of an array of size one become more popular?

 struct Foo { // .. size_t size; int data; }; // .. for (int i = 0; i < p->size; ++i) (&p->data)[i] = i; 
+6
source share
4 answers

Access to the array beyond its borders is undefined behavior. For example, your debugger may decide to insert channel arrays on each side of the array.

The smart thing is to just use std::vector , which is what it is for. Structural hacking is an old C-ism and redundant in C ++.

+8
source

With the second version, you cannot use the pretty direct array syntax. You cannot do

 p->data[i] 

but need to do

 (&p->data)[i] 

which looks much more ugly.

+7
source

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

+5
source

Because p->data[i] shorter and more readable than (&p->data)[i] .

+2
source

Source: https://habr.com/ru/post/893449/


All Articles