user630983
user630983

Reputation: 947

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);
      }

Upvotes: 1

Views: 571

Answers (4)

vtha
vtha

Reputation: 587

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.

Upvotes: 0

Argote
Argote

Reputation: 2155

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.

Upvotes: 1

Roland Rabien
Roland Rabien

Reputation: 8836

The snippet invokes undefined behaviour. The result can be anything, from crashing to unexpected output.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355207

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.

Upvotes: 8

Related Questions