首页 > 解决方案 > C++ 打印奇怪的行为(潜在的内存泄漏?)

问题描述

我正在运行一些 C++ 代码,并注意到一些奇怪的行为。例如,我的 std::cout 打印只打印出我告诉它打印的字符串的一部分。

这是我的代码的一小部分(此代码被重复调用):

std::ofstream file;
file.open("cout_img.txt", std::ofstream::out | std::ofstream::app);
std::streambuf* sbuf = std::cout.rdbuf();
std::cout.rdbuf(file.rdbuf());
std::cout << "Reached Display Function NOW";
std::string frame_file_name = std::string("demo") + std::to_string(saveImgNum) + std::string(".bmp");
std::cout << frame_file_name + '\n';

例如,在本节中,我每次只打印“splay Function NOW”,而不是完整的字符串“Reached Display Function NOW”。我什至没有打印出 frame_file_name 变量。

这是否意味着我在某处遇到内存泄漏?如果是这样,我发布的代码部分看起来是否可疑?是因为我必须释放变量,例如 std::string 变量吗?

我还能寻找什么?如果这有所作为,我正在使用 CPython API(嵌入在 C++ 中的 Python)。

非常感谢!

标签: c++memory

解决方案


如果您只想写入文件(作为控制台替换/日志),那么没有理由通过std::cout.

我把你的片段剪下来了。这个:

int main()
{
    std::ofstream file;
    file.open("cout_img.txt", std::ofstream::out | std::ofstream::app);

    file << "Reached Display Function NOW\n";
    std::string frame_file_name = std::string("demo") + std::to_string(17 /*saveImgNum*/) + std::string(".bmp");
    file << frame_file_name + '\n';

    return 0;
}

生成一个文件cout_img.txt,其中包含:

Reached Display Function NOW
demo17.bmp

编辑:此外,您还可以在 Windows 应用程序中启用控制台。快速搜索导致此答案。将以下代码添加到您的WinMain,控制台将工作:

    AllocConsole();
    #pragma warning( disable : 4996 )
    freopen("conin$", "r", stdin);
    freopen("conout$", "w", stdout);
    freopen("conout$", "w", stderr);
    printf("Debugging Window:\n");
    std::cout << "Testing the console 1 2 3" << std::endl;

如果您进行更彻底的搜索,您甚至可以找到不使用已弃用方法的方法 ( freopen)。但正如那里所示,它确实向我刚刚创建的用于测试的 Windows 应用程序添加了一个正常运行的控制台。


推荐阅读