Given a pointer-to-array in C, can we malloc to it enough memory for extra elements (beyond the specified array size) and then safely access those elements using either the [] operator or pointer arithmetic?
Consider this example:
int (*foo)[ 10 ]; //Declare pointer to array of ten ints
foo = malloc( sizeof( int ) * 20 ); //Allocate memory for TWENTY ints
(*foo)[ 15 ] = 100; //Access element in "extra" space via [] operator
*( *foo + 16 ) = 200; //Access element in "extra" space via pointer arithmetic
printf( "%d\n", *( *foo + 15 ) ); //Prints 100
printf( "%d\n", (*foo)[ 16 ] ); //Prints 200
This code compiles fine and produces correct results in gcc. However, I'm not sure if it invokes undefined behavior.
Thanks!
What you're doing trigger undefined behavior because you're reading/writing past the bounds of an array of
int
of size 10.The proper way to access this memory is to use 2D array access. So instead of this:
Which is equivalent to this:
Do this: