gpt4 book ai didi

c - 如何解释下面的C代码片段?

转载 作者:行者123 更新时间:2023-11-30 20:02:08 26 4
gpt4 key购买 nike

海湾合作委员会版本:

海湾合作委员会4.4.3

代码片段:

#include <stdio.h>
struct str {
int len;
char s[0];
};

struct test {
struct str *p_str;
};

int main()
{
struct test t = { 0 };
if (t.p_str->s) // FLAG_0
printf("here!");
printf(t.p_str->s); // FLAG_1
return 0;
}

运行代码时出现错误:段错误

我使用gdb来调试。我发现它在 FLAG_1

处崩溃

我对此很困惑。

它在 FLAG_0 处运行正常,但在 FLAG_1 处崩溃。为什么?

同时,我发现t.p_str的值为0x00。我不明白 if 情况没问题。

注意:代码仅供学习!

最佳答案

由于 s 是一个数组,而不是指针,因此它永远不会为空。因此编译器可以随意省略检查,并假设它不为空。如果这样做,那么 FLAG_0 将不会尝试取消引用空指针,因此此时您不会遇到段错误。

当然,它可以自由地做任何想做的事情,因为程序具有未定义的行为。

关于c - 如何解释下面的C代码片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23426425/

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