以下代码运行编译器选项 -O3
与 -O0
结果不同的输出:
#include <stdlib.h>
#include <stdio.h>
int main(){
int *p = (int*)malloc(sizeof(int));
int *q = (int*)realloc(p, sizeof(int));
*p = 1;
*q = 2;
if (p == q)
printf("%d %d", *p, *q);
return 0;
}
我对结果感到非常惊讶。
使用 clang 3.4、3.5 ( http://goo.gl/sDLvrq) 编译
使用编译器选项
-O0
— 输出:2 2使用编译器选项
-O3
— 输出:1 2
这是一个错误吗?
有趣的是,如果我稍微修改一下代码 ( http://goo.gl/QwrozF ) 它的行为符合预期。
int *p = (int*)malloc(sizeof(int));
*p = 1;
在 gcc 上测试它似乎工作正常。
最佳答案
在realloc
之后,p
不再有效。
关于c++ - 应用编译器选项 -00 与 -03 在 clang 上调用 malloc 的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440999/