In a solution I posted I got comments that the solution contains Undefined Behavior. However, I do not see how. The basic of the solution posted is:
typedef struct {
int n;
int a[1];
} t_x;
void example(void)
{
int i;
t_x *t= malloc (sizeof(t_x) + 99*sizeof(int));
t->n= 100;
for (i=0; i < t->n; i++)
t->a[i]= i;
free(t);
}
The comment of UB centered on whether the array now has 1 element (as declared) or has 100 elements (as allocated).
The parts of the standard quoted were 6.5.6 (pointer/int addition) and 6.5.2.1 (array subscripting)
"6.5.6 defines what happens when you add a pointer and an integer. The resulting pointer points to a corresponding element of the array, if such an element exists, or to one element past the end. The result is undefined otherwise."
"6.5.2.1 defines what
a[n]
means in terms ofa+n
. It follows that you cannot saya[n]
if a doesn't have at leastn+1
elements."
With both quotes the commenter seems to imply that element a[99]
would not exist, however, looking at the memory lay-out it clearly exists:
Please help me understand if/why this is UB and what types of UB I may expect.