Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validity of the code

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?

like image 450
Prasoon Saurav Avatar asked Jan 10 '10 04:01

Prasoon Saurav


People also ask

What is a valid code check?

What Is a Validation Code? A validation code—also known as a CVV, CV2, or CVV2 code—is a series of three or four numbers located on the front or back of a credit card. It is intended to provide an additional layer of security for credit card transactions that take place online or over the phone.

How do you create a valid code?

To ensure you have valid code, simply run your code through a code validator, like the W3C Code Validator. There are many other tools available that incorporate the same test suite as the W3C Validator. Note: ARIA attributes will be marked as errors in some Web pages like pre-HTML5 pages.


1 Answers

Your array is two arrays of int[2], while your function populate() treats it as a single array of int[4]. Depending on exactly how the compiler decides to align the elements of array, this may not be a valid assumption.

Specifically, when j is 2 and you try to access arr[2], this is outside the bounds of main's array[0] and is therefore invalid.

like image 130
Greg Hewgill Avatar answered Oct 28 '22 12:10

Greg Hewgill