在动态分配的内存上使用指针算法的未定义行为

Undefined behavior with pointer arithmetic on dynamically allocated memory

我可能误解了这一点,但 c99 规范是否禁止在动态分配的内存上进行任何形式的指针运算?

从 6.5.6p7...

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

... 指向不在数组中的对象的指针被视为指向包含 1 个项目的数组(当使用运算符 + 和 - 时)。然后在这个片段中:

char *make_array (void) {
    char *p = malloc(2*sizeof(*p));
    p[0] = 1; // valid
    p[1] = 2; // invalid ?
    return p;
}

...第二个下标p[1]无效?由于 p 指向一个不在数组中的对象,因此它被视为指向一个包含一项的数组中的对象,然后从 6.5.6p8...

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 the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. 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. 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.

...我们有未定义的行为,因为我们解引用了数组边界(隐含的长度为 1)。

编辑:

好的,为了弄清楚更多让我困惑的地方,让我们一步一步来:

1.) p[1] 定义为 *(p+1).
2.) p 指向一个不在数组内的对象,因此它被视为指向长度为 1 的数组内的对象,以便评估 p+1.
3.) p+1 产生一个指针 1 经过 p 暗示指向的数组。
4.) *(p+1) 执行无效的取消引用。

来自 C99,7.20.3 - 内存管理函数(强调我的):

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).

这意味着分配的内存可以作为 char 的数组访问(根据您的示例),因此指针算法定义明确。