K
Keith Thompson
The comp.lang.c-recommended way to invoke malloc() is, of course:
some_type *ptr;
ptr = malloc(count * sizeof *ptr);
But what if (in C99 only) ptr is a pointer to a VLA (variable-length
array) type? Consider this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n = 10;
typedef char VLA[n];
VLA *ptr = NULL;
ptr = malloc(3 * sizeof *ptr);
printf("sizeof *ptr = %d\n", (int)sizeof *ptr);
return 0;
}
As far as I can tell, this is legal in C99. The operand of sizeof in
the malloc call is *ptr, which is of a variable-length array type,
which means, according to C99 6.5.3.4p2, that it's evaluated. Since
ptr is a null pointer at that point, evaluating *ptr invokes undefined
behavior.
I'm not suggesting that we should drop the clc-approved method for the
normal case; I suspect that malloc calls involving VLA types are going
to be vanishingly rare. It's just an interesting quirk of the
language.
Incidentally, the above program compiles and executes without error
under gcc in its C99ish mode. That doesn't prove anything, since it's
one possible consequence of UB.
I think I'll post in comp.std.c asking just what C99 6.5.3.4p2 really
means and why the operand is evaluated.
some_type *ptr;
ptr = malloc(count * sizeof *ptr);
But what if (in C99 only) ptr is a pointer to a VLA (variable-length
array) type? Consider this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n = 10;
typedef char VLA[n];
VLA *ptr = NULL;
ptr = malloc(3 * sizeof *ptr);
printf("sizeof *ptr = %d\n", (int)sizeof *ptr);
return 0;
}
As far as I can tell, this is legal in C99. The operand of sizeof in
the malloc call is *ptr, which is of a variable-length array type,
which means, according to C99 6.5.3.4p2, that it's evaluated. Since
ptr is a null pointer at that point, evaluating *ptr invokes undefined
behavior.
I'm not suggesting that we should drop the clc-approved method for the
normal case; I suspect that malloc calls involving VLA types are going
to be vanishingly rare. It's just an interesting quirk of the
language.
Incidentally, the above program compiles and executes without error
under gcc in its C99ish mode. That doesn't prove anything, since it's
one possible consequence of UB.
I think I'll post in comp.std.c asking just what C99 6.5.3.4p2 really
means and why the operand is evaluated.