-2

I wrote the following c program:

int main() 
 {
     char a[1];
     char b[6]="hello\0";
     int c,  i;

     for(i = 0; (c = getchar()) != EOF; i++) 
         a[i] = c;
     for(i = 0; i  < 5; i++) 
         printf("%c", b[i]);

 }

Why when I give "bye" in input the program print "helby"? I thought 'b' should be saved in a[0], 'y' in b[0] and 'e' in b[1]. Thank you in advice!

sworwitz
  • 19
  • 7
  • 3
    That `while` loop has the syntax of a `for` loop and does not compile. Please post the [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that shows the problem. – Weather Vane Oct 10 '16 at 18:49
  • Thanks, I edited it – sworwitz Oct 10 '16 at 18:50
  • your result is not reproduced :( ... check this : https://ideone.com/oAWAiw , here we get `hello` as output when input is `bye` – Cherubim Oct 10 '16 at 18:52
  • It is correct that `'b'` is stored in `a[0]`, everything else is undefined behaviour. – mch Oct 10 '16 at 18:52
  • 1
    I think this depends entirely on the compiler. When I ran this on ideone.com, it printed `hello`. Note also that `"hello\0" is a string literal that includes an implicit null as well as the explicit null you encoded, so it actually has length 7. (See [this thread](http://stackoverflow.com/questions/17943411/do-string-literals-that-end-with-a-null-terminator-contain-an-extra-null-termina), for instance.) – Ted Hopp Oct 10 '16 at 18:52
  • your result is not reproduced :( ... check this : https://ideone.com/oAWAiw , here we get `hello` as output when input is `bye` – Cherubim Oct 10 '16 at 18:52
  • The very first statement in `main` is `char a[1];` so within the corrected loop `a[i] = c;` will break the system with *undefined behaviour*. Do not try playing tricks in C, there are few enough safeguards anyway. – Weather Vane Oct 10 '16 at 18:55

2 Answers2

1

You assume that a is immediately followed by b in memory. That is not necessarily the case.

Reading/writing past the end of an array is undefined behavior, so compilers are free to arrange local variables in any order they choose.

On my particular machine, if b is declared before a, then a appears just before b in memory and I get the output you expect. However, as you can see from the other answers and comments that behavior is not reliable because of undefined behavior.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

Why when I give "bye" in input the program print "helby"?

In the program you are trying to access beyond the bounds of array a[] in this loop:

 for(i = 0; (c = getchar()) != EOF; i++) 
     a[i] = c; //only defined behaviour for `i = 0`

for example when you give bye as input,

a[0] -> overwritten with b
a[1] -> undefined behaviour as you are accessing out of bounds
a[2] -> same as a[1]

here you can see that nowhere the b[] array is changed.

it leads to undefined behaviour. So your output can be anything (from nothing to everything)

Cherubim
  • 5,287
  • 3
  • 20
  • 37