取消引用包含对象地址的越界指针(数组数组) [英] Dereferencing an out of bound pointer that contains the address of an object (array of array)

查看:34
本文介绍了取消引用包含对象地址的越界指针(数组数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于不同的 REF 值,以下定义是否明确?

Is the following well defined, for different values of REF?

#include <stdio.h>

#define REF 1
#define S 1

int main(void) {
    int a[2][S] = {{1},{2}};
    int *q = REF ? a[1] : 0;
    int *p = a[0] + S;
    memcpy (&q, &p, sizeof q);
    printf ("q[0] = %d\n", q[0]);
    return 0;
}

注意p指向a[0]的最后一个元素之后,而不是数组a[0]中的元素>,因此不可解引用.但是p中存储的地址是a[1][0]的地址.p 在语义上(故意?)指向到"(好吧,从)a[0] 但在物理上指向 a[1].

Note that p points to the after the last element of a[0], not to an element in the array a[0], hence not dereferenceable. But the address stored in p is the address of a[1][0]. p semantically (intentionally?) points "to" (well, out of) a[0] but physically points into a[1].

当原始指针的位模式副本仅在物理上指向对象时,它能否在语义上指向一个对象?

Can a copy of the bit pattern of a pointer point semantically to an object when the original only physically does?

另见

我用不同的角度"问了基本相同的 C/C++ 问题:

I have asked essentially the same C/C++ question with a different "angle":

  • Are pointer variables just integers with some operators or are they "mystical"?
  • Is memcpy of a pointer the same as assignment?
  • Overwriting an object with an object of same type (C++ only)

推荐答案

Given

int blah(int x, int y)
{
  int a[2][5];
  a[1][0] = x;
  a[0][y] = 9;
  return a[1][0];
}

标准中没有任何内容会禁止编译器将其重新编码为 int blah(int x, int y) { return x;},也不会在 y>=5 时捕获(或做任何事情),因为 a[0]a[1]> 是每个有五个元素的不同数组.在间接访问结构的最后一个元素是单元素数组的情况下,编译器通常包含允许对该数组进行指针算术以产生指向结构外存储的指针的代码.虽然此类指针算术会被标准禁止,但它支持有用的构造,而这些构造在 C99 之前无法以任何符合标准的方式实际实现.

nothing in the Standard would forbid a compiler from recoding that as int blah(int x, int y) { return x; }, nor trapping (or doing anything whatsoever) when y>=5, since a[0] and a[1] are distinct arrays of five elements each. In cases where the last element of an indirectly-accessed structure is a single-element array, compilers have generally included code to allow pointer arithmetic on that array to yield a pointer to storage outside the structure. While such pointer arithmetic would be forbidden by the Standard, it enables useful constructs which could not be practically implemented in any standard-compliant fashion prior to C99.

请注意,将 5 添加到 a[0] 将产生一个 int*a[1] 比较相同,但事实是过去的"指针与标识内存中下一个对象的指针相比较并不意味着它可以安全地用于访问后一个对象.此类访问可能通常有效,但这并不意味着编译器必须让它们这样做.

Note that adding 5 to a[0] would yield an int* that compares identical to a[1], but the fact that a "one-past" pointer compares equal to a pointer which identifes the next object in memory does not imply that it may be safely used to access the latter object. Such accesses may often work, but that doesn't mean compilers are required to have them do so.

这篇关于取消引用包含对象地址的越界指针(数组数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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