This program is also printing some garbage value which it should not print.
Input: My name is Priyansh
Expected Output: yM eman si hsnayirP
Output: yM eman si hsnayirP a■³vÚCvõeQ
Why am i getting this garbage value? It is working fine in GDB online Debugger
Yikes - people are still using “Turbo C” in 2020?
Anyway, if the input ends on anything other than a space, by the time we loop back around to
while(str[i]!='\0')
the variable i can be one past the null-terminator of str, and the contents of str[i] will be undefined.
To see this, simply put:
assert(i < strlen(str));
after the:
printf("%s ",rev);
++i;
(you’ll need to #include <assert.h>) and try it with any input that doesn’t end with a space.
Edit:
Apparently, it still triggers the assertion even when the input does end with a space.
Edit2:
My mistake: the assertion you should be adding is:
assert(i < strlen(str) + 1);
(strlen(str) would be the position of the null-terminator, which we are allowed to dereference; strlen(str) + 1 is the beginning of the “danger-zone”).
So I think I was right the first time in that this shouldn’t create garbage if the input ends with a space