使用argv []时出现分段错误

时间:2014-09-02 22:33:24

标签: c

尝试在程序中输入少于5个参数时,我一直遇到“分段错误”。我认识Java,但我是C的新手,我只是不确定发生了什么。我只是简单地尝试将用户输入的kg(作为参数)转换为Prius'的重量,它将是小数。

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


int main(int argc, char *argv[]) //Argc is the argument count, argv is the argument vector
{

    //Initialize the toyota/user variables  
    int toyota = 1325; //Toyota weight in kg
    int paramOne = atoi(argv[1]);
    int paramTwo = atoi(argv[2]);
    int paramThree = atoi(argv[3]);
    int paramFour = atoi(argv[4]);

    //This if will check to see if there are too many parameters    
    if (argc >= 5)
    {
        printf("Error: Too many parameters.\n");
        printf("Usage: ./HW1 arg1 [arg2 ... arg4].\n");
    }

    //This if will check to see if there are too few parameters
    if (argc < 2)
    {
        printf("Error: Too few parameters.\n");
        printf("Usage: ./HW1 arg1 [arg2 ... arg4.\n");
    }


    //If there are a correct amount of parameters, this will print the TP count
    if ((argc >= 1) && (argc <= 4))
    {
        printf("%d number of parameters.\n", argc);     

        if(argc >= 1)
        {

            printf("%d kg = %d TP.\n", paramOne, paramOne/toyota); //Parameter divided by TP
        }

        if(argc >= 2)
        {
            printf("%d kg = %d TP.\n", paramTwo, paramTwo/toyota);  
        }

        if(argc >= 3)
        {
            printf("%d kg = %d TP.\n", paramThree, paramThree/toyota);  
        }

        if(argc >= 4)
        {
            printf("%d kg = %d TP.\n", paramFour, paramFour/toyota);    
        }




    }

}

3 个答案:

答案 0 :(得分:4)

int paramOne = atoi(argv[1]);
int paramTwo = atoi(argv[2]);
int paramThree = atoi(argv[3]);
int paramFour = atoi(argv[4]);

如果argc <= 4这些调用调用未定义的行为。如果没有足够的参数,请先测试argc,不要调用atoi

答案 1 :(得分:1)

如果有人输入./your_program param1 param2,并且您的程序调用了atoi(argv[3]),那么atoi会收到错误的指针。这是因为argv[3]中的值从未设置(因为您的程序仅使用两个参数调用)。 atoi现在正试图取消引用给定的垃圾(因为它认为它是指向char的合法指针),因此导致了Segmention错误。

答案 2 :(得分:1)

没有上限的替代方法:

int i = 1;
while (argv[i] != NULL)
{
    int param = atoi(argv[i]);
    printf("%d kg = %d TP.\n", param, param/toyota);
    i++;
}