Ryan
Ryan

Reputation: 107

Segmentation fault while using argv[]

I keep running into a "Segmentation Fault" while trying to enter less than 5 parameters into the program. I know Java, but am new to C, and I'm just not sure what is going on. I'm just simply trying to convert user entered kg (as a parameter) to the number of Prius' in weight it would be, to the decimal.

#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);    
        }




    }

}

Upvotes: 2

Views: 13108

Answers (3)

dreamlax
dreamlax

Reputation: 95395

An alternative approach which has no upper bound:

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

Upvotes: 1

Philipp Murry
Philipp Murry

Reputation: 1682

If someone inputs ./your_program param1 param2, and your program calls atoi(argv[3]), then atoi gets handed an incorrect pointer. This is because the value inside argv[3] was never set (since your program was called only with two parameters). atoi is now trying to dereference the given garbage (because it thinks it's a legit pointer to a char), therefore causing a Segmention Fault.

Upvotes: 1

ouah
ouah

Reputation: 145899

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

If argc <= 4 these calls invoke undefined behavior. Test argc before and don't call atoi if there are not enough arguments.

Upvotes: 5

Related Questions