代码的有效性 [英] Validity of the code

查看:165
本文介绍了代码的有效性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  void populate(int * arr)
{ int j = 0; j <4; ++ j)
arr [j] = 0;
}

int main()
{
int array [2] [2];
populate(& array [0] [0]);
}

在本地社区有关于此的讨论,无论代码是有效的不是(我应该提到它的名字吗?)。一个人说他调用UB,因为它违反了



C ++标准($ 5.7 / 5 [expr.add])


如果指针操作数和结果指向同一个数组对象的元素,或者指向一个超过数组对象的最后一个元素,则评估不应产生溢出; 否则,行为未定义


但我没有看到代码的任何错误,代码是完全适合我。



所以,我只想知道这个代码是否有效? c> c>

code> int [2] ,而您的函数 populate()将其视为单个数组 int [4] 。根据编译器如何决定对齐数组的元素,这可能不是一个有效的假设。



具体来说,当 j 是2并且您尝试访问 arr [2] 时, c $ c> main 的数组[0] ,因此无效。


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?

解决方案

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.

这篇关于代码的有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆