Dan
Dan

Reputation: 21

Cerr Not Working

I wrote a function that takes two numbers from command line and multiples it, and if the argc is not 3 it is supposed to output a cerr line; however it doesn't work. Am I doing something wrong?

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
 int product;
 int first_num = atoi(argv[1]);
 int second_num = atoi(argv[2]);
 product = first_num * second_num;
 if(argc != 3)
 {
    cerr << "Usage: ./multiply first_num second_num" << endl;
    exit(1);
 }
 else
 {
    cout << product << endl;
 }
}

Instead of the cerr printing, a zsh: segmentation fault ./multiply comes out.

Upvotes: 0

Views: 1614

Answers (1)

nos
nos

Reputation: 229108

If you don't pass in any arguments to your program, argv[1] is a null pointer and argv[2] doesn't exist, you're not allowed to access that index. So you don't want to try to pass that to atoi(). Check first, then look at what's at argv[1]/argv[2] only if you're sure they actually exists.

 if(argc != 3)
 {
    cerr << "Usage: ./multiply first_num second_num" << endl;
    exit(1);
 }
 else
 {
    int product;
    int first_num = atoi(argv[1]);
    int second_num = atoi(argv[2]);
    product = first_num * second_num;
    cout << product << endl;
 }

Upvotes: 3

Related Questions