c++ - 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)。
非常感谢!
解决方案
如果您只想写入文件(作为控制台替换/日志),那么没有理由通过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 应用程序添加了一个正常运行的控制台。
推荐阅读
- c# - C#:如何要求对方法进行错误处理?
- spring - gridfstemplate.store(in, url, fileType, metadata); 不存储 contentType
- android - Flutter调试发布模式,发布模式开启日志
- python - Django 模型(动态?)
- python - 由于 pycairo 1.20 无法导入 matplotlib
- c++ - .cpp 文件中具有相同类型但主体不同的内联函数
- mysql - Sequelize upsert 始终在发布请求时创建/插入新条目,而不是更新匹配用户名的数据。MySQL数据库
- javascript - 在 useEffect 钩子中获取元素的高度
- sql - 带有日期时间参数的 EXEC sp_executesql?
- c# - 获取最新评论的 Sql 查询添加了 3 个表