Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Application exit with code -8 before even tries to divide by 0?

I have code like this:

#include <stdio.h>
#include <stdint.h>

int main() {
    uint8_t result = 0;
    uint8_t a = 0;
    printf("Trying to divide by %d...\n", a);
    result = (1/a != 0);
    printf("%d\n", result);
    
    return 0;
}

I have tried this in online compiler here: https://www.mycompiler.io/new/c

And this is the result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[Execution complete with exit code -8]

I expected "Trying to divide by 0…" to be printed out, and then application should exit.

But the application exits before it prints anything.

Is it normal C behavior or some glitch of online compiler?

>Solution :

I can see two possible explanations here

First, it’s important to know that undefined behavior can time travel back in time. There is no guarantee that the program will run fine until the problematic line. This may occur because the compiler might think that it would be better to reorder things like this:

uint8_t a = 0;
uint8_t result = (1/a != 0);
printf("Trying to divide by %d...\n", a);

The compiler is allowed to do this, because it’s allowed to assume that division by zero will never happen.

Second, it could be the case that the output needs to be flushed. Whenever you want to make sure that a printout gets visible on screen before doing something else, use fflush(stdout). It might make a difference if you do this:

printf("Trying to divide by %d...\n", a);
fflush(stdout);
result = (1/a != 0);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading