2

I have a small code to look whats the argv's

#include <iostream>

using namespace std;
int main(int argc, char** argv){

    cout << "===================" << endl;
    cout << "argc: " << argc << endl << endl;
    cout << "argv[0]: " << argv[0] << endl << endl;
    cout << "argv[1]: " << argv[1] << endl << endl;
    //cout << "argv[2]: " << argv[2] << endl << endl; //Program crash
    cout << "===================" << endl;

    return 0;
}

When I start the program with no parameters:

argc is 1
argv[0] is the execution path
argv[1] should be out of range and the program should crash, but the program terminates like I write return. If I check the errorlevel it is 9009
If I try to access argv[2] the program crashs as expected

(When I start the program with one parameter everything works fine)

Why it doesn't crash like argv[2] when I access argv[1]?
And for what stand errorlevel 9009?

Thanks in advance

Morchul
  • 1,987
  • 1
  • 7
  • 21

2 Answers2

7

It doesn't crash because argv is defined as a null terminated array. The last element is argv[argc], that always holds a null pointer. You aren't accessing out of bounds for the array.

But...

You pass a null pointer value to std::ostream's operator<< for c-strings. That is undefined in and of itself, so your program isn't exactly well behaved in this case either.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
3

... and the program should crash.

No, no, no!

The whole point of undefined behaviour is that it's, well, undefined.

Literally anything is allowed to happen when you dereference a null pointer (which argv[argc] is required to be, and ostream::operator<< will try to dereference it) including, and this is the most insidious aspect of UB, it working as expected sometimes, or it failing with a frankly bizarre return code :-)

But, bottom line, if you break the contract with the standard, all bets are off. Don't do it.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    @Morchul: It may or it may not. It's totally up to the implementation what it returns under UB conditions. – paxdiablo Apr 10 '18 at 07:32