C++ program crashes when counter is used inside loop

257 views Asked by At

I am working on a very small program to find the divisors of an integer in C++. My main method pretty much cins an int to a var and calls the factor method with the int as the argument. Here's the code:

void factor(int num)
{
    for(int x = 0; x < ((num + 2) / 2); x++)
    {
        if((num % x) == 0)
        {
            cout << x << " ";
        }
    }
}

The program always crashes inside factor(). If I use this code, it runs fine:

void factor(int num)
{
    for(int x = 0; x < ((num + 2) / 2); x++)
    {
        {
            cout << x << " ";
        }
    }
}

So the problem is somewhere in the if((num % x) == 0). When I change that line to if((num % 2) == 0) or if((num % 5) == 0), it produces the right results (I'm using 32 as the test input).

I learned C++ a few years ago and forgot most of it, after running into this issue I copied the code word for word off of my previous solution to this problem (which worked). But the program still crashes whenever I try to access the loop counter.

I'm using Code::Blocks 13.12 with GCC "4.9.0 20140604 (prerelease)" on Arch Linux 64-bit.

4

There are 4 answers

0
Filip Roséen - refp On BEST ANSWER

The problem is that you have an division-by-zero in your first snippet, something which is undefined-behavior according to the standard (n3337):

5.6p4 Multiplicative operators [expr.mul]

The binary / operator yields the quotient, and the binary % operator yeilds the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined.


Since the program cannot calculate the value of such expression it will crash.

if((num % x) == 0)  // num % 0 on first iteration, application will crash, or order pizza
{
  cout << x << " ";
}
3
AudioBubble On

How can you do num%x when x is 0? Due to use of x when it is 0, program crashes.

This would cause a runtime error which I suppose would be SIGFPE.

0
George On

In the very first cycle of the for x has the value 0. num % x would require a division by 0 which is a mathematical non-sense and that is where is crashes.

You want to see all the divisors of the number (they divide the number and 0 is left to carry over). You should start the for cycle at 2. (1 is already a given - you could print him out directly, but you going to only half the number, so I suspect you are not interested in 1 and the number itself).

0
mrsan On

Try to start the loop from x = 1.

Starting from 0 does not make any sense, if you want to compute the factors of a number. The % operator computes the remainder of the divison num/x. A division by 0 does not make any sense, so the behavior of the operation is undefined. This means it can crash with one compiler/machine and can produce some sort of result on another compiler/machine.