简体   繁体   English

以下代码片段的输出应该是什么?为什么?

[英]What should be the output of this following code snippet and why?

What should be the output of this following code snippet and why? 以下代码片段的输出应该是什么?为什么?

     #include <stdio.h>
     #include <string.h>
     int main()
     {
        char ch = 'A';
        char str[3];
        strcpy(str, "ABCDE");
        printf("%c", ch);
      }

The output of this program could be anything because you overrun the buffer str and get undefined behavior. 该程序的输出可能是任何东西,因为您超出了缓冲区str并获得了未定义的行为。 In fact, the program might not output anything, it might crash, or it might do something far worse. 实际上,该程序可能不输出任何东西,它可能会崩溃,或者可能做得更糟。

The snippet invokes undefined behaviour. 该代码段调用了未定义的行为。 The result can be anything, from crashing to unexpected output. 结果可能是任何事情,从崩溃到意外输出。

As other have mentioned, this is undefined behavior since it would depend on the contents of the memory located aftr wherever str is allocated. 正如其他人提到的那样,这是未定义的行为,因为它取决于位于str分配后的afrr后面的内存的内容。 It will start with ABCDE but will run off into a random collection of bytes converted to chars or a crash. 它以ABCDE开头,但会变成随机的字节集合,这些字节转换为char或崩溃。

The output is undefined. 输出未定义。 In linux, I am getting the output D because I think the data stored in stack from bottom to top. 在Linux中,我得到输出D,因为我认为存储在堆栈中的数据是从下到上的。 So, ch is stored at the bottom, and str is stored just above it. 因此,ch存储在底部,str存储在其上方。 now you are overwriting str with two bytes extra, which is resulting in corrupting ch variable, which may result in displaying the D as output. 现在,您要用额外的两个字节覆盖str,这会导致ch变量损坏,这可能会导致将D显示为输出。 Again, this depends upon compiler and operating system you are running. 同样,这取决于您正在运行的编译器和操作系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM