Search code examples
cerror-handlingsegmentation-faultcommand-line-argumentsmultiplication

Segmentation fault when running C program for integer multiplication with insufficient arguments


I am working on a C program that is supposed to multiply two integers and print the result of the multiplication. If the program does not receive exactly 2 arguments, it should print "Error" and return 1.

I compiled the program with the following command:

gcc -Wall -pedantic -Werror -Wextra -std=gnu89 3-mul.c -o mul

When I run the program with ./mul int1 int2 or ./mul int1 int2 int3, it outputs the correct result. However, when I run it with just ./mul, it produces a segmentation fault, rather than printing "Error" as I expect.

Here is my code:

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

int main (int argc, char *argv)
{
  int x = atoi(argv[1])
  int y = atoi(argv[2])

if (argc == 3)
   {
       printf("%d\n", x * y);
   }
else
   { 
       printf("Error\n");
       return 1;
    }

return 0;
}

What am I doing wrong, and how can I modify my code to produce the expected output when called with insufficient arguments?

Thanks in advance for your help.


Solution

  • You want this:

    int main(int argc, char* argv[]) // char* argv[] here
    {
      if (argc != 3)                // test argc *before* dereferencing argv[1] and argv[2]
      {
        printf("Error\n");
        return 1;
      }
    
      int x = atoi(argv[1]);
      int y = atoi(argv[2]);
      printf("%d\n", x * y);  
      return 0;
    }
    

    You are dereferencing argv[1] and argv[2] before testing if argc is 3. Instructions are executed sequencially. If you execute your program without arguments on the command line, argc will be 1 and argv[1] is out of bounds hence the seg fault.

    Moreover the signature of main is wrong, it should be int main (int argc, char *argv[]). The second argument of main is an array of pointers to char.