这是boost::asio::ssl
示例,它没有内存泄漏:
int main(int argc, char* argv[])
{
#if defined(WIN32) || defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
try
{
boost::asio::io_context io_context;
boost::asio::ip::tcp::resolver resolver(io_context);
boost::asio::ip::tcp::resolver::results_type endpoints =
resolver.resolve("127.0.0.1", "9443");
boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
ctx.load_verify_file("ca.pem");
client c(io_context, ctx, endpoints);
io_context.run();
while (getchar() != 'q');
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
但是,如果我将代码更改为以下内容:
int main(int argc, char* argv[])
{
#if defined(WIN32) || defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
try
{
// just used a thread to execute the ssl test,the rest of the code is exactly the same
std::thread([]()
{
boost::asio::io_context io_context;
boost::asio::ip::tcp::resolver resolver(io_context);
boost::asio::ip::tcp::resolver::results_type endpoints =
resolver.resolve("127.0.0.1", "9443");
boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
ctx.load_verify_file("ca.pem");
client c(io_context, ctx, endpoints);
io_context.run();
while (getchar() != 'q');
}).join();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
然后,有一个内存泄漏:
Detected memory leaks!
Dumping objects ->
{2182} normal block at 0x000000000034C8B0, 8 bytes long.
Data: < > 00 00 00 00 01 00 00 00
{128} normal block at 0x000000000035AB30, 520 bytes long.
Data: < > 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Object dump complete.
我发现asio::ssl
内存泄漏了很长时间,但从未解决过,我发现如果主线程中没有调用io_context::run
,那么就会出现内存泄漏。有人能帮助我吗?
答案 0 :(得分:0)
这实际上不是泄漏。静态构造函数中分配的任何内存都可能被错误地标识为泄漏。
要解决此问题:
#include "stdafx.h"
#include <gtest/gtest.h>
#include "MemLeakInstrumentation.h"
#include "MemLeakListener.h"
#include "PreventFalseMemoryLeaksFromStatics.hpp"
static int q = prevent_false_memory_leaks_from_statics( L"UnitTest.CouloirAFX" );
int main( int argc, char* argv[] )
{
testing::InitGoogleTest( &argc, argv );
auto& listeners = testing::UnitTest::GetInstance()->listeners();
listeners.Append( new gte::MemLeakListener );
const auto result = RUN_ALL_TESTS();
return result;
}
static int prevent_false_memory_leaks_from_statics( Couloir::String UnitTestName )
{
Couloir::Directory BoostStaticInit( L"C:\\Dev\\Couloir\\Generic\\PFM\\UnitTest.CouloirPFM" );
boost::asio::io_context ioc;
ssl::context AsioStaticInit{ ssl::context::sslv23_client };