当 new 运算符重载并输出到 std::cout 时,使用 Clang 编译的 C++ 程序崩溃

C++ program compiled with Clang crashes when new operator is overloaded and outputs to std::cout

我在 Windows 10.

上使用 Clang 版本 10.0.0

这个节目

#include <iostream>
// without this operator the program works just fine
void* operator new(std::size_t nrOfBytes) {
    std::cout << "allocate " << nrOfBytes << " bytes on heap" << std::endl;
    void* p = malloc(nrOfBytes);
    if (p) {
        return p;
    } else {
        throw std::bad_alloc{};
    }
}
int main() {
    printf("START\n");
    return 0;
}

使用

编译后崩溃,代码为 -1073741819 return

clang++ Main.cpp -std=c++17

当然,在没有重载 new 运算符的情况下,同样的 Clang 调用会生成无错误的程序。

有什么提示吗?

尝试从 "new" 中删除 cout 操作。 可能有些流操作需要其他 "new"?