Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ argv[1] terminate the program with return value 9009

Tags:

c++

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

like image 340
Morchul Avatar asked Jan 24 '26 10:01

Morchul


2 Answers

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.

like image 162
StoryTeller - Unslander Monica Avatar answered Jan 27 '26 02:01

StoryTeller - Unslander Monica


... 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.

like image 42
paxdiablo Avatar answered Jan 27 '26 00:01

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!