Posts

Showing posts with the label integer-overflow

Implicit conversion double to unsigned long overflow c++

Implicit conversion double to unsigned long overflow c++ I'm testing a timer based on the ctime library using the clock() function. Please note that the code that follows is only for test purposes. #include <ctime> unsigned long Elapsed(void); clock_t start = 0; clock_t stop = 0; int main() { start = std::clock(); while(1) { sleep(1); cout << "Elapsed seconds: " << Elapsed() << endl; } return 0; } unsigned long Elapsed() { stop = std::clock(); clock_t ticks = stop - start; double seconds = (double)ticks / CLOCKS_PER_SEC; //CLOCK_PER_SEC = 1 milion return seconds; } As you can see I'm performing an implicit conversion from double to unsigned long when Elapsed() returns the calculated value. The unsigned long limit for a 32 bit system is 2,147,483,647 and I get overflow after Elapsed() returns 2146. Looks like the function converts "ticks" to unsigned long, CLOCK_PER_SEC to unsigned long and then it returns th...