【问题标题】:SIGSEGV Error in short C code短 C 代码中的 SIGSEGV 错误
【发布时间】:2015-10-02 00:14:33
【问题描述】:

所以,作为一个对 C 相当陌生的人,我遇到了我的第一个 SIGSEGV 错误。 它出现在一个简短的 C 程序中,该程序旨在成为“猜数字”游戏。它由一个比较两个数字的自定义函数和一个 do-while 循环及其内部的输入组成。 start 和 do-while 循环:

#include<stdio.h>

int checkNum(int num1, int num2); //See below for explanation

int main(void) {
    int input=0, rand=3; //"Random" number has fixed value for testing

    do {
        printf("Enter number from 0-10: "); //There is not actual range yet
        scanf("%d",input); //Get input
    } while(checkNum(input, rand)); //Checks if difference != 0
}

比较函数:

//Function for comparing input with "random" number
int checkNum(int num1,int num2) { //The two numbers that get compared; First one: input, Second one: "random" rumber
    if(num1==num2) {
        printf("Correct. The random number was %d",num2);
    } else if(num1<num2) {
        printf("Wrong. The random number is bigger.");
    } else if(num1>num2) {
        printf("Wrong. The random number is smaller.");
    }
    return num2-num1; //Return the difference, leads to 0 if equal
}

我怀疑函数中的错误是由于缺少使用指针引起的,但据我所知,指针在这里似乎没有必要:我没有更改函数中的单个变量,并且返回只减去两个值(我假设是给定的)。

我希望我的错误不是太愚蠢,并且我要感谢所有可以提供帮助或尝试提供帮助的人。 (我可以发布我的处理器值,虽然我不确定这是否会有所帮助;如果需要更多信息进行调试,请告诉我)

【问题讨论】:

    标签: c function pointers segmentation-fault


    【解决方案1】:

    这个:

        scanf("%d",input); //Get input
    

    应该是:

        scanf("%d",&input); //Get input
                  ^^^
    

    专业提示:始终在启用警告的情况下进行编译(例如gcc -Wall ...),编译器会很乐意指出此类简单错误,从而为您节省大量时间和烦恼。

    【讨论】:

    • 非常感谢您的快速帮助;问题已解决,但让我有点困惑的是,我的 c 编辑器(“Dev-cpp”,一个 c++ 和 c 编译器)中的“调试”功能有时似乎也会导致 sigsegv;但是它停止出现,现在可以正常工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多