Home > Enterprise >  Pointer-to-array, malloc, and out-of-bounds access
Pointer-to-array, malloc, and out-of-bounds access

Time:10-31

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!

CodePudding user response:

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:

(*foo)[15] = 100;

Which is equivalent to this:

foo[0][15] = 100;

Do this:

foo[1][5] = 100;

CodePudding user response:

I would allocate it a bit different way:

foo = malloc( sizeof( *foo ) * nrows );

it will allocate 2D array having 10 clomns and nrows rowas.

The best way to access the array is using indexes

foo[row][column]
  • Related