In C, is it "legal" to under-allocate memory to a pointer-to-array if we then only access elements that fall within the allocated memory? Or does this invoke undefined behavior?
int (*foo)[ 10 ]; //Pointer to array of 10 ints
foo = malloc( sizeof( int ) * 5 ); //Under-allocation!
//Only enough memory for 5 ints
//Now we only ever access (*foo)[ 0 - 4 ]
If this, in and of itself, is not undefined behavior, then could accessing another, unrelated object whose memory address happens to fall within the address space of unallocated part of the array cause a strict-aliasing violation?
This is undefined behavior.
foois supposed to point to an object (or the first of an array of objects) of typeint[10]. This is considered an object of array type, defined in section 6.2.5p20 of the C standardThe part I've highlighted in bold is the important part. An
int[10]is therefore a contiguously allocated set of 10 objects of typeint.You don't allocate enough space, so the expression
*foowhich has typeint[10]accesses an object of that type, but doing so reads past the end of an allocated memory segment.