开发者

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[开发者_C百科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. 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. It will start with ABCDE but will run off into a random collection of bytes converted to chars or a crash.


The output is undefined. In linux, I am getting the output D because I think the data stored in stack from bottom to top. So, ch is stored at the bottom, and str is stored just above it. 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. Again, this depends upon compiler and operating system you are running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜