Strange crash at runtime
does anyone know, why the following codes is crashing, when it is compiled with g++?
#include <iostream>
unsigned long getSumDivisors(const unsigned long number) {
unsigned long sum = 0;
for(unsigned long i = 0; i < number; ++ i) {
if(number % i == 0) {
sum += i;
}
}
return sum;
}
int main() {
std::cout << getSumDivisors(5);
return 0;
}
when i remove sum += i; it wont crash.
I tried to compile it under windows and linux linaro with
g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3 Copyright © 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
and
g++ (tdm-2) 4.8.1 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
It causes an SIGFPE. The reason is because of the division by zero:
if(number % i == 0)
You can fix it here:
for(unsigned long i = 1; i < number; ++ i)
The SIGFPE will be happening usually on systems with a floating point unit, which raises an exception in this case. The actual behaviour depens on the implmentation details and is undefined. On older systems with an floating point emulation library it may return 0 or or a random result.
你除以0,因为我在for循环中以0开始,然后尝试获得分区的剩余部分
The first time through the loop, you have i = 0. You can't divide by zero, so your "number % i" is bad. It appears on your system that's causing a crash.
I wonder if removing "sum += i" causes some sort of optimization such that the if condition is never checked because of the empty body.
链接地址: http://www.djcxy.com/p/49708.html上一篇: 取消对类的成员函数的NULL指针
下一篇: 运行时奇怪的崩溃