为什么代码 printf(“%s ”,str);当我没有在 C 中定义变量 str 时,工作正常并且不会触发任何错误

问题描述 投票:0回答:1
int main(int argc, char const *argv[])
{
    printf("%s\n", str);
    return 0;
}

我在某处读到这样的代码会在Linux操作系统中触发陷阱,但我不明白这怎么会只触发操作系统的陷阱而不是导致终止进程或启动中断的错误。我什至没有定义 str 和 IDE(与带有插件的代码,等等)也警告我

identifier "str" is undefined c/c++20

[Done] exited with code=0 in 1.64 seconds

这是我的程序(storage.c)的结果。

我试过了

gcc storage.c -o storage
这就是我得到的

storage.c: In function ‘main’:
storage.c:19:20: error: ‘str’ undeclared (first use in this function)
   19 |     printf("%s\n", str);
      |                    ^~~
storage.c:19:20: note: each undeclared identifier is reported only once for each function it appears in

gcc明确指出有错误 但是当我运行时

./storage
什么也没发生,就像它完美地工作一样。但这段代码显然有缺陷。所以我真的很想理解这种行为。为什么这个程序没有因错误代码而终止? trap和OS在这个程序中扮演什么角色?

c linux gcc undefined trap
1个回答
0
投票

在 C 语言中,代码 printf("%s ", str); 如果在使用变量 str 之前未定义或声明,则可能会触发编译错误。您所描述的行为(它可以正常工作而不会触发错误)可能是由于可能性所致。

© www.soinside.com 2019 - 2024. All rights reserved.