gpt4 book ai didi

c - if block 内的变量显示在调用堆栈中,即使 if 语句未评估为 true

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:05 25 4
gpt4 key购买 nike

我有一段 C 代码,如下所示-

在.c 文件中-

1    custom_data_type2 myFunction1(custom_data_type1 a, custom_data_type2 b)
2 {
3 int c=foo();
4 custom_data_type3 t;
5 check_for_ir_path();
6 ...
7 ...
8 }
9
10 custom_data_type4 myFunction2(custom_data_type3 c, const void* d)
11 {
12 custom_data_type4 e;
13 struct custom_data_type5 f;
14 check_for_ir_path();
15 ...
16 temp = myFunction1(...);
17 return temp;
18 }

在头文件中-

1    void CRASH_DUMP(int *i)
2 __attribute__((noinline));
3
4 #define INTRPT_FORCE_DUMMY_STACK 3
5
6 #define check_for_ir_path() { \
7 if (checkfunc1() && !checkfunc2()) { \
8 int temp = INTRPT_FORCE_DUMMY_STACK; \
9 ...
10 CRASH_DUMP(&sv);\
11 }\
12 }\

在未知情况下,发生崩溃。使用 GDB 处理核心转储后,我们得到的调用堆栈如下 -

#0  0x00007ffa589d9619 in myFunction1 [...] 
(custom_data_type1=0x8080808080808080, custom_data_type2=0x7ff9d77f76b8) at ../xxx/yyy/zzz.c:5

temp = 32761

t = <optimized out>



#1 0x00007ffa589d8f91 in myFunction2 [...]

(custom_data_type3=<optimized out>, d=0x7ff9d77f7748) at ../xxx/yyy/zzz.c:16

temp = 167937677

f = {

...

}

如果您看到代码,check_for_ir_path 是从 myFunction1()myFunction2() 调用的。

check_for_ir_path 中,if block 中有一个检查,如 - checkfunc1() && !checkfunc2()。如果该检查的计算结果为 TRUE,则会触发 SIGSEGV 并故意使进程崩溃。并且仅当该条件通过时才声明变量 temp

现在,如果您查看调用堆栈,甚至可以在 StackFrame_1 中看到局部变量 temp。然而它并没有在函数 myFunction2 中崩溃。这怎么可能?

如果我在语句 int temp = INTRPT_FORCE_DUMMY_STACK; 之后声明另一个变量,说 'int temp',它不会显示为 bt full 的一部分

这怎么可能?

最佳答案

编译器可以在不改变程序结果的情况下以任何方式重新组织您的代码。所以如果你写:

void foo()
{
if (something)
{
int sv;
...
}
}

允许编译器将其更改为等同于:

void foo()
{
int sv;
if (something)
{
...
}
}

不管 something 是真还是假。

但是编译器必须确保编译失败:

void foo()
{
if (something)
{
int sv;
...
}
sv = whatever; // Compiler error....
}

关于c - if block 内的变量显示在调用堆栈中,即使 if 语句未评估为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52171254/

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