The program is supposed to multiply two integers and print the result of the multiplication. If the program doesn't receive 2 arguments it should print Error and return 1.
I compiled it with < gcc -Wall -pedantic -Werror -Wextra -std=gnu89 3-mul.c -o mul>
when I run it with <./mul int int > or <./mul int int int > it's outputting correct result but when I run it with just <./mul > it's saying segmentation fault and I expect it to output error. My code is below. Thanks in advance
#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;
}
CodePudding user response:
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
.