Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it undefined behaviour to access an array beyond its end, if that area is allocated? [duplicate]

Possible Duplicate:
Is the “struct hack” technically undefined behavior?

Normally accessing an array beyond its end is undefined behavior in C. For example:

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

Is it still undefined behavior if I know that the memory area after the end of the array has been allocated, with 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 have seen this patten used in several places to make a variable length struct, and it seems to work in practice. Is it technically undefined behavior?

like image 396
Tor Klingberg Avatar asked Sep 10 '12 15:09

Tor Klingberg


1 Answers

What you are describing is affectionately called "the struct hack". It's not clear if it's completely okay, but it was and is widely used.

As of late (C99), it has started to be replaced by the "flexible array member", where you're allowed to put an int data[]; field if it's the last field in the struct.

like image 67
cnicutar Avatar answered Oct 11 '22 18:10

cnicutar