开发者

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

开发者 https://www.devze.com 2023-02-14 14:13 出处:网络
What should be the output of this following code snippet and why? #include <stdio.h> #include <string.h>

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

精彩评论

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