下面C段代码编译运行后p1,p2的状态是什么?
char *p1 = malloc(5);
char *p2 = p1 - 3;
*p2 = '\0';
最佳答案
如果您在简单机器上将此 C 代码直接转换为简单机器代码,则 char *p2 = p1 - 3;
会将 p2
设置为指向 3内存中比 p1
早的字节,并且 *p2 = '\0'
会将零写入不正确的位置。我们不知道那个位置是什么,所以我们不能说效果是什么。
然而,现代编译器一般不会将 C 代码直接转化为简单的机器代码。他们解释 C 代码并对其进行复杂的优化。因此,了解发生的情况需要使用 C 标准或所用编译器的文档。
关于这段代码,C 标准告诉我们什么?对于 p1 - 3
,适用 C 2018 6.5.6 8 中关于指针加法的规则:
When an expression that has integer type is added to or subtracted from a pointer,… 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.
因为p1
指向malloc
提供的object的一个元素(可以作为数组使用),而p1 - 3
确实不指向该数组的元素,则该行为未由 C 标准定义。因此,如果我们以C标准作为理解的基础,一旦p1 - 3
被评估,我们就不能说程序的行为或p1
的状态是什么p2
是。
关于c - 指向内存负地址的 C 编译器行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53579833/