C++打印奇怪的行为(潜在的内存泄漏?

C++ Print Weird Behavior (Potential Memory Leak?)

本文关键字:内存 泄漏 打印 C++      更新时间:2023-10-16

我正在运行一些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",而不是完整的字符串"REACH Display FUNCTION NOW"。我什至没有打印出frame_file_name变量。

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

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

非常感谢!

如果您只想写入文件(作为控制台替换/日志(,则没有理由通过std::cout重定向输出。

我拿了你的片段并把它剪下来。这:

int main()
{
std::ofstream file;
file.open("cout_img.txt", std::ofstream::out | std::ofstream::app);
file << "Reached Display Function NOWn";
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 应用程序添加了一个功能正常的控制台。