Code only works if all variables are set to 0. UB?

This code is interrupted randomly, correctly identifying some numerical palindromes and does not work on others.

#include <stdio.h> int main(int argc, char *argv[]) { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or not\n"); scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10; } if ( n == reverse ) printf("%d is a palindrome number.\n", n); else printf("%d is not a palindrome number.\n", n); return 0; } 

For example, the above code incorrectly says that "87678" is not a numeric palindrome.

Checking the return scanf() shows that it is succeeding, and printing the value of n correct for input 87678.

However, the code correctly says that "4554" is a palindrome.

However, adding:

 n = reverse = temp = 0; 

before the first printf() program runs correctly all the time. So what happens in the first version? Is this some kind of undefined behavior when variables are not initialized before use?

EDIT: will later provide an assembly of the compiled version that does not see what the compiler does.

+6
source share
3 answers

If sizeof(int) less than 4, you get a compiler error, your hardware is malfunctioning, or you have some form of data corruption on your system.

To answer the question: no, there is no undefined behavior anywhere in your program (provided that scanf() really does not work).

Try running memtest on your system to eliminate memory problems: http://www.memtest.org

+4
source

It sounds very much like a compiler error, as it works with later versions of gcc. I would be very interested to see the output of gcc -S (pastebin, please?), And also to find out the compilation command that you are using. (especially the level of optimization).

+2
source

Unlike Java, C has no default value for int. You can refer to this post as it discusses this similar issue.

-3
source

All Articles