gpt4 book ai didi

c - 交换 C 中的 Printf 操作

转载 作者:行者123 更新时间:2023-11-30 18:53:37 25 4
gpt4 key购买 nike

/*
Can you interchange the execution order of the printf() statements?!
Notes:
- problem occurs in 32-bit Ubuntu 14.04
- problem occurs in 64-bit Ubuntu 14.04
*/

#include <stdio.h>

int * addition(int a, int b) {
int c = a + b;
int *d = &c;
return d;
}

int main(void) {
int result = *(addition(1, 2));
int *result_ptr = addition(1, 2);
printf("result = %d\n", *result_ptr);
printf("result = %d\n", result);
return 0;
}

问题说交换行的顺序 printf("result = %d\n", *result_ptr);

printf("result = %d\n", result);

将导致不同的输出。但是当我在 Ubuntu 中编译并运行这两个代码时,结果是相同的,两个输出都是 3 3。这个问题应该只发生在 Ubuntu 中。

最佳答案

两个版本都是未定义的行为,因为您返回本地分配变量的地址 ( c ),从技术上讲,这是堆栈上的地址。一旦函数退出,它就不再有效。所以问题本身是无效的,输出也可能是“米老鼠”。

编辑:从技术上讲,您获得“预期”输出的事实只是因为 printf碰巧访问与您的 addition 相同的堆栈位置函数之间没有发生清理。但这确实只是“偶然”。

关于c - 交换 C 中的 Printf 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32539473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com