访问一个外边界指针包含一个对象的地址(阵列的阵列) [英] Dereferencing an out of bound pointer that contains the address of an object (array of array)

查看:121
本文介绍了访问一个外边界指针包含一个对象的地址(阵列的阵列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的明确定义,为 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 的地址的[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)

推荐答案

由于

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

没有在标准将从重新编码,作为 INT嗒嗒(INT X,int y)对{返回X禁止编译器; } ,也不能俘获(或做任何事情任何),当 Y'GT = 5 ,因为 A [0] A [1] 各五行不同的阵列。在的情况下间接访问的结构的最后一个元素是一个单元素数组,编译器通常均包含code键允许该阵列上指针运算,得到一个指向结构外部存储。虽然这种指针运算将由标准被禁止的,它使所不能实际上在任何标准兼容的方式之前,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] ,而是一个过去指针比较等于其identifes存储器中的下一个对象,并不意味着它可以安全地用于访问一个指针的事实后者的对象。此类访问可能经常工作,但编译器都要求有他们这样做并不意味着

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天全站免登陆