0

While checking if a string is palindrome or not when I print the reversed string 'v' is automatically appended here why is that? And also if I remove the palindrome checking part of the code then the 'v' is not appended ,why is that?(May be it is undefined behaviour but how? the code seems alright). I tried to find out how this program is undefined behaviour but I don't know whats wrong. And also this program should print nothing but it prints some string, I can't figure out why it does so.

#include<stdio.h>
int main(){
    int i,j;
    char string[100],reverse[100];

    printf("enter a string:\n");

    fflush(stdin);
    scanf("%s",string);

    for(j=0;string[j]!='\0';j++);

    for(i=0;i<=j;i++){ 
        /* I know if here is <= (it is intetional)
        it will go upto one more than the string.
        If we suppose so then '\0' should be swapped in front of 
        the string so no sting should have been printed but it prints string. */ 
        

        printf("%d\n",i);
        reverse[i]=string[j-1-i];
    }

    printf("%s ,%d, %d",reverse,j,i);

    int is_palindrome=1;

    for( i=0;i<j;i++){
        if(string[i]!=reverse[i]){
            is_palindrome=0;
            break;
        }
        
    }

    if(is_palindrome){
        printf("\nis palindrome");
    }
    else{
        printf("\nis not palindrome");
    }
   
}
  • 3
    `reverse[i]=string[j-1-i];` when `i == j` will result in `-1` and `string[-1]` indeed makes your program have _undefined behavior_. – Ted Lyngmo Aug 30 '21 at 10:09
  • 1
    Note that `fflush(stdin);` is also *undefined behaviour*. – Weather Vane Aug 30 '21 at 10:22
  • should't we use fflush(stdin); before scanf so that the computer wont accidentally record enter key as as input for scanf – Coder Manish Aug 30 '21 at 10:30
  • 2
    @CoderManish No. [`fflush(stdin);`](https://en.cppreference.com/w/c/io/fflush) should _never_ be done: "_For input streams (and for update streams on which the last operation was input), the behavior is undefined._" – Ted Lyngmo Aug 30 '21 at 10:36
  • 2
    See [Using fflush(stdin)](https://stackoverflow.com/q/2979209/673852) for extended discussion of this particular question. – Ruslan Aug 30 '21 at 10:52

0 Answers0