Is this undefined behavior for accessing an array beyond if this area is allocated?

Possible duplicate:
Technically, the behavior is undefined "struct hack>

Usually accessing an array beyond is an undefined behavior in C. For example:

int foo[1];
foo[5] = 1; //Undefined behavior

Is this behavior still undefined if I know that the memory area after the end of the array was allocated, using malloc or on the stack? Here is an example:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  int len;
  int data[1];
} MyStruct;

int main(void)
{
  MyStruct *foo = malloc(sizeof(MyStruct) + sizeof(int) * 10);
  foo->data[5] = 1;
}

I saw this patten used in several places to create a variable-length structure and seems to work in practice. Is this technically undefined behavior?

+5
source share
3 answers

, , "struct hack" . , , .

(C99), " ", int data[];, .

+6

6.5.6 :

8 - [...] , , , . [...] , *, .

malloc, :

7.22.3

1 - [...] , , , ( ). .

, , ​​ , MyStruct, , . (6.7.2.1:18).

, J.2 Undefined :

1 - Undefined : [...]
- , .
- , *, .
- , , -, ( lvalue a[1][7] int a[4][5]).

, , Undefined :

  MyStruct *foo = malloc(sizeof(MyStruct) + sizeof(int) * 10);
  foo->data[5] = 1;

:

  MyStruct *foo = malloc(sizeof(MyStruct) + sizeof(int) * 10);
  ((int *) foo)[(offsetof(MyStruct, data) / sizeof(int)) + 5] = 1;

++ ; 3.9.2 [basic.compound] :

3 - [...] T A, cv T*, A, , , , .

C , . restrict.

+2

C99 6.7.2.1.

C99: , "struct hack" , :

...

. , undefined, p->items , , . : , (, int items[INT_MAX];), undefined .

, , C89 " ", . " ". "-1" malloc , struct hack, .

Structural hacking is undefined behavior, since not only the C specification itself is supported (I'm sure there are citations in other answers), but the committee even wrote down its opinion.

So the answer is yes, it is undefined behavior according to the standard document, but it is well defined according to the de facto C standard. I assume that most compiler authors are very familiar with the hack. From GCC tree-vrp.c:

   /* Accesses after the end of arrays of size 0 (gcc
      extension) and 1 are likely intentional ("struct
      hack").  */

I think there are good chances that you can even find hackers in the compiler test suites.

+2
source

All Articles