void push(char item)
printf("Enter a sentence: ");
i = strlen(str);
str[i] = '\0';
rev[j++] = pop();
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
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));
(you’ll need to
#include <assert.h>) and try it with any input that doesn’t end with a space.
Apparently, it still triggers the assertion even when the input does end with a space.
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
then we can also add
You shouldn’t be adding
str[i] = '\0';
in the first place; it’s pointless (
str[strlen(str)] will be
\0, by definition).
Instead of adding Yet Another Null Terminator, it’s better to just get your "increment
i" logic right in the first place
Some Indian high schools still teach C++ using TurboC .
I was doing C++ in Turbo C during my high school time.