How to understand the solution?

int main(int argc, char** argv)
{
    try {
            char *p2 = NULL;
            cout << "p2:" << strlen(p2) <<endl; 
                    cout << "mark";
        }
        catch (...) {
            cout << "caught exception" <<endl;
        }
    return 0;
}

The conclusion p2:, therefore cout << "mark";, is neither cout << "caught exception" <<endl;launched nor why?

+3
source share
5 answers

In C ++, dereferencing a NULL pointer causes undefined behavior , which means that everything can happen: a computer can explode, a function can return an arbitrary value, a program can be killed by an exception of the operating system (which, unlike a C ++ expression, cannot be detected by try-catch).

In short, does not do this .

(, , ), (, SEH Windows).

+6

POSIX - SIGSEGV , strlen(p2), p2 - NULL.

, segfaults ++.

+5

undefined. , - . , strlen ( , x86), .

++ .

+3

strlen() , C C . , . ( .)

+2

strlen (NULL) NULL. , try-catch. . , .

, () NULL. NULL - , ( ), . catch - ( strlen):

if(p2 == NULL)
    throw 1;

You forgot to add an endl manipulator to the line that prints the "mark". It should be:

cout << "mark" << endl;
0
source

Source: https://habr.com/ru/post/1774322/


All Articles