简体   繁体   中英

C++ exception string displayed as garbage on Mac OS with Xcode and CLion

I'm learning C++. I tried the following code on my MBP, macOS 10.14.6, Xcode 11.0.

include <iostream>

using std::cout;
using std::endl;
using std::cerr;

void errthrow();

int main(int argc, const char * argv[]) {
    try {
        errthrow();
    } catch (const char* pEx) {
        cerr << pEx << endl;
    }
}

void errthrow()
{
    char message[10] {"Exception"};
    throw message;
}

Instead of getting string "Exception" in the terminal, text "0\365\277\357\376" was outputted.

Compiled with CLion, the output is something like this: `'���

The code works fine on Windows 10, VS 2019.

Your code has undefined behavior. This is a very subtle issue that really only applies to arrays. When you do

char message[10] {"Exception"};

message is local to the function. When you throw it, instead of copying the array, what happens is the array decays into a pointer, and it is the pointer that gets copied. Because of this you are left with a pointer to message but message no longer exists after you exit the function.

If you need to throw a c-string, then the correct method if

throw "message to throw";

This works because "message to throw" is implcitly static and because of that it will live for the life of the program. When you catch the pointer, the pointer still refers to a valid object unlike when you returned it from an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM