0

I have an issue with C++ code. I want to pass argument to my code, but sometimes it will be empty. My code is very simple.

#include <iostream>

int main(int argc, char **argv) {

  std::cout << argv[0] << std::endl;
  std::cout << argv[1] << std::endl;

}

What I want is to show empty argument in case it is not provided. What I get is

./main
Segmentation fault: 11
L. F.
  • 19,445
  • 8
  • 48
  • 82
kelahcim
  • 51
  • 7

1 Answers1

6

You need to ensure that two arguments are actually present in argv before reading them. Reading an uninitialized variable is undefined behaviour in C++.

#include <iostream>

int main(int argc, char **argv) {
    if (argc >= 2) {
        std::cout << argv[0] << std::endl;
        std::cout << argv[1] << std::endl;
    }
}

The above would be OK, since argc tells you the number of elements in argv and the code above then only reads them if there is actually two or more elements to read.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70