递减指针出界;递增入界 [英] Decrementing a pointer out of bounds; incrementing it into bounds

查看:204
本文介绍了递减指针出界;递增入界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作中的4号线和/或5惹未定义行为:

 的#include<&stdio.h中GT;
INT主要(无效)
{
  个char [] =富;
  字符* P = S - 1; / *行4 * /
  的printf(%S \\ n,P + 1); / *行5 * /
  返回0;
}


解决方案

  

执行以下操作中的4号线和/或5惹未定义行为:


4号线的是未定义行为因为指针数组边界或者一个过去的数组边界内没有指向。虽然这是有效的一点一点过去数组边界你不能解引用该元素。

C99标准草案中的相关部分 6.5.6 添加剂运营商第8段的:


  

当有整型的前pression被加上或减去从指针,
  结果具有指针操作数的类型。 [...]如果这两个指针操作数和结果的指向同一个数组对象的元素,或者一个过去的数组对象后,该评估也不得产生溢出的最后一个元素; ,否则,这种行为是未定义


段落的结尾说,你不尊重过去1最后一个元素:


  

[...]如果结果点中的一个过去的数组对象的最后一个元素,它的不得用作目*运算符的操作数被评估


Does the following provoke undefined behavior in line 4 and/or 5:

#include <stdio.h>
int main(void)
{
  char s[] = "foo";
  char * p = s - 1;      /* line 4 */
  printf("%s\n", p + 1); /* line 5 */
  return 0;
}

解决方案

Does the following provoke undefined behavior in line 4 and/or 5:

Yes, Line 4 is undefined behavior since the pointer is not pointing within the array bounds or one past the array bounds. Although it is valid to point one past the array bounds you can not dereference that element.

The relevant section in the c99 draft standard is 6.5.6 Additive operators paragraph 8:

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. [...] 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.

The end of paragraph says that you shall not deference one past the last element:

[...] If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated

这篇关于递减指针出界;递增入界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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