这是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,那么就会有内存泄漏。有人能帮我吗?
发布于 2018-11-17 23:58:52
这并不是真正的泄密。在静态构造函数中分配的任何内存都可能被错误地标识为泄漏。
要解决此问题,请执行以下操作:
#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 };https://stackoverflow.com/questions/48148019
复制相似问题