Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug that disappears when attempting to study it

Tags:

c++

debugging

This is the most weird thing that has ever happened to me when programming in C++.

This is my main file:

#include <iostream>
#include "lib/utils.h"

using namespace std;

int main(int argc, const char *argv[]) {
    cout << bin2dec(101000010);
    return 0;
}

and this is lib/utils.cpp:

#include <iostream>
#include "utils.h"

int bin2dec(int bin) {
    // 101000010
    int dec;
    //std::cout << "";  // If you uncomment this, it works.
    for (int i = 1; bin > 0; i *= 2, bin /= 10) {
        if (bin % 2 == 1) {
            dec += i;
        }
    }
    return dec;
}

The program compiles with no warnings, and when run, it outputs 450. 450 is not 101000010 in decimal, 322 is. The first weird thing is that the difference between 482 and 322 is exactly 128. This happens with any binary number you try to convert. But what's REALLY weird, is that when I tried to output the value of bin and dec inside the for in an attempt to debug the function, it suddenly started working correctly.

Basically, for some reason, if you std::cout something before the function returns, it works. If you don't, it adds 128 to the result.

I'm using g++ 4.6.0, and compiling like this:

g++ -c   -D NDEBUG -O2     -o 10.o 10.cpp
g++ -c   -D NDEBUG -O2     -o lib/utils.o lib/utils.cpp
g++  -o 10   -Wl,-S  10.o lib/utils.o lib/menu.o 
like image 870
Gerardo Marset Avatar asked May 29 '11 19:05

Gerardo Marset


1 Answers

You're not initializing dec.

int dec = 0;
like image 182
Evan Avatar answered Oct 07 '22 09:10

Evan