C++打印奇怪的行为(潜在的内存泄漏?
C++ Print Weird Behavior (Potential Memory Leak?)
我正在运行一些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 应用程序添加了一个功能正常的控制台。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏