Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

c - Dereferencing an out of bound pointer that contains the address of an object (array of array)

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
", q[0]);
    return 0;
}

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?

SEE ALSO

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...