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

后端 未结 2 1021
小蘑菇
小蘑菇 2020-12-07 00:40

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

#include 

#define REF 1
#define S 1

int main(void) {
    int a[2][S         


        
2条回答
  •  太阳男子
    2020-12-07 01:07

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

    There is no such distinction effectively, because a[0] + S is the same as a[1], assuming that inner array is declared with S size.

    The following:

    int a[2][S];
    

    declares two-elements array, where each element is an array of S-elements of type int. Arrays are stored contigously and there is no padding before/between/after its elements.

    We will prove, that a[0] + S == a[1] holds. It can be rewritten as:

    *(a + 0) + S == *(a + 1)
    

    By pointer arithmetic, RHS adds 1 * sizeof(*a) bytes to a, that is the same as size of the inner array. LHS is little more complex, as addition is performed after dereference of a, thus it adds:

    S * sizeof(**a) bytes,

    Both sides are guaranteed to be equal when they point to the same object (the same memory location), of the same type. Hence you could rewrite it into "absolute" one-byte form as:

    (char *)a + S * sizeof(**a) == (char *)a + sizeof(*a)
    

    This reduces into:

    S * sizeof(**a) == sizeof(*a)
    

    We know, that sub-array *a has S elements of type of **a (i.e. int), so both offsets are the same. Q.E.D.

提交回复
热议问题