Reverse of word in a sentence

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

char s[100];
int top=-1;

void push(char item)
{
    s[++top]=item;
}

char pop()
{
    return s[top--];
}

void revsenword()
{
    char str[100],rev[100];
    int i,j;
    printf("Enter a sentence: ");
    gets(str);
    i = strlen(str);
    str[i] = '\0';
    i=0;
    while(str[i]!='\0')
    {
        while(str[i]!=' '&&str[i]!='\0')
        {
            push(str[i]);
            i++;
        }
        j=0;
        while(top!=-1)
        {
            rev[j++] = pop();
        }
        rev[j] ='\0';
        printf("%s ",rev);
        ++i;
    }
}

void main()
{
    revsenword();
    getch();
}

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? :frowning:

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 :slight_smile:

4 Likes

then we can also add str[++i]='\0' after str[i]='\0.

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 :slight_smile:

2 Likes

Some Indian high schools still teach C++ using TurboC .
I was doing C++ in Turbo C during my high school time.

2 Likes