简体   繁体   中英

Why is the following code giving runtime error SIGSEGV

I am writing the solution to a programming problem. The problem is as follows:

Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.

I have pasted my code below. I am getting segmentation fault when I submit this solution. Can someone point out what's wrong with this code? Any help will be much appreciated.

#include <stdio.h>

int main(void) {
    int number = 0;
    while (1)
    {
        int c = getchar();
        if (c != EOF)
        {
            number = number * 10 + c;
        }
        else
        {
            //const char value = number;
            if (number != 42)
            {
                printf(number);
                printf("\n");
                number = 0;
            }
            else
            {
                return 0;
            }
        }
    }
}

In your code

printf(number);

is invalid. You're missing the required format specifier with printf() . You want to write

printf("%d", number);

Also, printf() being a variadic function , it can accept one or more arguments and as long as that criteria is met, compilation will not fail. However, this instance, will cause undefined behaviour because of mismatched argument type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM