Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This code fails randomly by correctly identifying some numeric palindromes and failing 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 "87678" isn't a numeric palindrome.

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

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

However, by adding:

n = reverse = temp = 0;

before the first printf() the program appears to work correctly all the time. So what is happening in the first version? Is this some sort of undefined behavior when the variables aren't initialized before use?

EDIT: Will later provide the assembly of the compiled version that is failing to see what the compiler is doing.

like image 280
Chimera Avatar asked Oct 29 '12 09:10

Chimera


2 Answers

Unless sizeof(int) is less than 4, you've either hit a compiler bug, your hardware is malfunctioning, or you have some form of data corruption going on in your system.

To answer the question: no, there's no undefined behavior anywhere in your program (assuming the scanf() really doesn't fail).

Try running memtest on your system to rule out RAM issues: http://www.memtest.org

like image 81
Nikos C. Avatar answered Sep 24 '22 07:09

Nikos C.


It sounds very much like you have a compiler error since this works with later versions of gcc. I'd be very interested to see the output of gcc -S (pastebin please?) and also to know the compile command you are using. (optimization level especially).

like image 33
dave Avatar answered Sep 20 '22 07:09

dave