-1

I have written this code:

#include <stdio.h>

int main() {
    printf("Works");
    int base = 1;
    do {
        if (base > 1) {
            for (int i = 0; i <= base; i++) {
                if ((base % i) == 0) {
                    break;
                } else {
                    printf("%d ", base);
                }
            }
        }
        base += 1;
    } while (1);
    return 0;
}

It compiles perfectly, but when I run it the terminal just closes, I have no idea how to debug this, as I am very new to making programs in c.

Edit: This is supposed to generate primes forever.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Chadderbox
  • 55
  • 1
  • 5
  • 9
    Use this as a reason to learn how to run your code in a debugger... – DisappointedByUnaccountableMod Feb 11 '20 at 16:31
  • 2
    As @FiddlingBits pointed this `base % i` causes `SIGFPE`. probably you need to starts `i` from `1` instead of `0`. Or change `base % i` --> `base % (i+1)`. Alternatively you need to learn how to handle such problem if you know the expected behavior [what does C/C++ handler SIGFPE?](https://stackoverflow.com/questions/14905947/what-does-c-c-handler-sigfpe) Graceful exit is better than crash. – Achal Feb 11 '20 at 16:36
  • 1
    After this `printf("%d ", base);` you need to flush the `stdout` buffer, for e.g `fflush(stdout);` or `printf("%d \n", base);` – Achal Feb 11 '20 at 16:43
  • @Achal Just don't ever write a signal handler with non-async-signal-safe garbage like `std::cout ...` in it... – Andrew Henle Feb 11 '20 at 16:44
  • *"This is supposed to generate primes forever."* You know this is not possible, right? Eventually `int base` would overflow, which also results in undefined behavior. – Fiddling Bits Feb 11 '20 at 16:51
  • Try using `continue` instead of `break`. – Jona Feb 11 '20 at 17:04

6 Answers6

5

Your problem is here:

for (int i = 0; i <= base; i++)
{
    if ((base % i) == 0)
    ...

The first iteration results in a modulo 0 which is undefined behavior. In your case your program crashes.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
5

The right hand side of your modulo operator is zero, which is undefined behavior:

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

  • C Standard, subclause 6.5.5 [ISO/IEC 9899:2011]

Side Note: You didn't see anything from printf because it is buffered -- it doesn't print directly to the console for historical/performance reasons. Usually it is line buffered, so adding a newline \n to the printf lines should force the buffer to print out to the console.

5

On the first iteration, the following statement:

if ((base % i) == 0)

Is equivalent to

if ((base % 0) == 0)
           ^^^

Which causes a Divide By Zero, (exact words in my environment.) which, in the C language means undefined behavior, and which in turn means anything can happen. In your case, results in crashing the program. Ironically, this is about one of the absolute best results you can expect with UB. The absolute worst thing would be that it appeared to work. (Then you would have a time-bomb bug, waiting to occur at some unexpected time.)

The fix is simply paying attention to your initial conditions.

for (int i = 0; i <= base; i++)

for (int i = 1; i <= base; i++)  
            ^^^  
ryyker
  • 22,849
  • 3
  • 43
  • 87
2

When you run a console application, a terminal window will be created for this.

After the program finishes, the terminal window will be closed.

If you don't want the program to automatically close, you can add getch() at the end of the program. This waits until you e.g. press enter(or until it reads something from the console).

Another possibility is to open the terminal by yourself and to start the application inside the terminal. In this case, the terminal won't be closed when the program finishes.

As other answers state, i in base%i can be 0 and the calculation results in undefined behaviour. For example the app could crash.

dan1st
  • 12,568
  • 8
  • 34
  • 67
0

The fact that the numbers are not printed is because in the for loop, it interprets the break statement and exit from the loop in the first iteration. Use continue instead of break as it will jump into the next iteration of the for loop.

Jona
  • 1,218
  • 1
  • 10
  • 20
0

The terminal closes because the program exits immediately with a Zero Divide exception.

The loop logic is flawed: you should start with i = 2 instead of i = 0 and you should iterate as long as i < base

Furthermore, you print every non divisor of the numbers tested, you should instead print the number if the nested loop exits normally. Here is a modified version:

#include <stdio.h>

int main() {
    printf("Works\n");
    int i, base;
    for (base = 2;; base += 1) {
        for (i = 2; i < base; i++) {
             if ((base % i) == 0)
                break;
        }
        if (i == base)
            printf("%d\n", base);
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189