“调试断言失败!表达式:_p!= nullptr”错误

时间:2019-10-02 12:34:30

标签: c command-line

error image我试图制作一个程序,该程序使用多个参数进行计算。 除了我所附的图片中的最后一个,一切都按我的预期工作。 每次我在命令行中输入两个以上的数字时,都会发生错误。

输入示例为:program1.exe 12 + 13-2 + 1

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


int main(int argc, char *argv[])
{
    int a, b, rst;
    int i;
    char opr;

    if (argc > 100)
    {
        printf("Too many arguments!\n");
        return 0;
    }
    else if (argc <= 1)
    {
        printf("There are no arguments!\n");
        return 0;
    }

    a = atoi(argv[1]);
    rst = a;
    if (argc == 2)
    {
        a = atoi(argv[1]);
    }
    else if (argc % 2 != 0)
    {
        printf("Invalid fomula!\n");
        exit(0);
    }
    else
    {
        for (i = 1; 2*i <= argc; i++)
        {
            b = atoi(argv[2 * i]);
            opr = argv[2 * i - 1];
            switch (opr)
            {
            case '+':rst = a + b;
                break;
            case '-':rst = a - b;
                break;
            }

            rst = a;
        }
    }
    printf("%d", rst);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

按原样运行代码,并将输入设置为:<program.exe> 2 + 5 空指针错误在这里发生:

for (i = 1; 2*i <= argc; i++)
        {
            b = atoi(argv[2 * i]);//Null pointer for i==2
            opr = argv[2 * i - 1];
            switch (opr)

因为没有argv[4]。结果为 undefined behavior

在不知道程序期望输入什么的情况下,不可能准确地进行纠正。因为您未指定,所以我最好的猜测是程序尝试从命令行读取一组参数,例如:

argv[0]          argv[1]   argv[2]   argv[3]
<program>.exe    1         +         2

然后将读取的值转换为变量,并使用两个数字和数学运算符(例如+-)执行数学运算。

假设这是基本目标,下面的示例将简化您现有的代码以执行这些步骤。注意对参数输入计数测试的更正,并降低循环索引:

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

/// test using:
// prog.exe 2 + 3 3 - 4 6 + 7

//results are:
//result 0: 5
//result 1: -1
//result 2: 13

typedef struct {
    int n1;
    char opr;
    int n2;
    int result;
} CALC;


int main(int argc, char *argv[])
{
    int i;
    // test for correct number of input arguments
    if((argc-1)%3 !=0)
    {
        printf("Wrong number of inputs.\n");
        return 0;
    }

    // read in, and assign variables (use array of struct)
    int max = (argc-1)/3;  //guaranteed viable only after determining multiples are correct from above
    //Get ALL input into array variables
    CALC calc[max];
    for (i=0;i<max;i++)
    {
        //convert inputs into usable variables
        calc[i].n1  = atoi(argv[i*3+1]);
        calc[i].opr = argv[i*3+2][0];
        calc[i].n2  = atoi(argv[i*3+3]);

        // perform calulations
        switch(calc[i].opr) {
            case '+':
                printf("result %d: %d\n", i, calc[i].n1 + calc[i].n2);
                break;
            case '-':
                printf("result %d: %d\n", i, calc[i].n1 - calc[i].n2);
                break;
        }
    }

    return 0;
}

大多数错误检查和功能返回值的测试都留给您。