Consider the following code :
void populate(int *arr)
{
for(int j=0;j<4;++j)
arr[j]=0;
}
int main()
{
int array[2][2];
populate(&array[0][0]);
}
There was a discussion regarding this on a local community whether the code is valid or not(Am I supposed to mention its name?). One guy was saying that it invokes UB because it violates
C++ Standard ($5.7/5 [expr.add])
"If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined."
But I don't see anything wrong with the code,the code is perfectly OK for me.
So, I just want to know is this code valid or not? Am I missing something?
Best Answer
Your
array
is two arrays ofint[2]
, while your functionpopulate()
treats it as a single array ofint[4]
. Depending on exactly how the compiler decides to align the elements ofarray
, this may not be a valid assumption.Specifically, when
j
is 2 and you try to accessarr[2]
, this is outside the bounds ofmain
'sarray[0]
and is therefore invalid.