"Segmentation Failure (Drop Core)" with Chassis

"Segmentation fault (core dumped)" appears when executing the following program. However, if I use the if ... else statement it doesn't give me any error. What is the reason for the error message in this case? How can I use a case statement without errors?

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

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

/*
    if (argc == 1){
        cout << argv[0] << endl;
    }else
    if (argc == 2){
        int n;
        n = atoi(argv[0]);
        cout << n << endl;
    }
*/
    switch (argc){
        case 1:{
            cout << argv[0] << endl;
        }
        case 2:{
            int n;
            n = atoi(argv[1]);
            cout << n << endl;
        }
    }

    return 0;
}

      

+3


source to share


1 answer


In your block, switch

no break

. Hence, every case will fail. This causes Undefined Behavior when argc

- 1

. You must break

exit the switch if you do not require a walkthrough.

switch (argc){
    case 1:{
        cout << argv[0] << endl;
        break;
    }
    case 2:{
        int n;
        n = atoi(argv[1]);
        cout << n << endl;
        break;
    }
}

      



From C ++ 17, when compilers warn you about implicit errors (not required), you can use an attribute [[fallthrough]]

to declare that your breakout is intentional.

+4


source







All Articles