Home > OS >  How to determine why a C program outputs unexpected messages?
How to determine why a C program outputs unexpected messages?

Time:08-08

I'm trying to program in C on Eclipse, I have installed and configured MinGW, but I have a problem that I don't understand:

I have some simple code:

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    int num1,num2;

    setbuf(stdout,NULL);

    printf("enter two numbers");
    scanf("%d%d",&num1,&num2);

    if(num1>num2){
        printf("num1 is greater than num2");

    }else{
        printf("num2 is greater than num1);
    }

    return 0;
}

After I compile and run, it shows me "Enter two numbers" and I enter two numbers, I can't see any further output and keyboard function doesn't work on console screen, it doesn't give me an error, but it does show some strange output on console:

<terminated>

<terminated>(exit value: -1.073.741.515) CPS:exe

CodePudding user response:

You're not reading in the values correctly:

scanf("%d%d",num1,num2);

The %d format specifier for scanf expect a int *, i.e. a pointer to an int, as an argument. It needs the address of a variable to be able to write a value to where that address is stored.

You're instead passing the current values of num1 and num2 which are essentially garbage values because the variables have not been written to.

You instead want:

scanf("%d%d",&num1,&num2);

CodePudding user response:

I don't kwon if the code you post is exactly the same as what you compiled, when I copy and compile the code you posted, gcc report an error at line:

printf("num2 is greater than num1);

There lost the ending quotation mark in printf(); After I fixed this error, it works well. My environment is

Linux DESKTOP-7VH0PN1 5.4.72-microsoft-standard-WSL2 #1 SMP Wed Oct 28 23:40:43 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

With gcc:

gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 Copyright (C) 2019 Free Software Foundation, Inc.

  • Related