使用Valgrind检测内存泄漏

时间:2013-02-06 07:49:10

标签: c++ mysql valgrind

我正在用C ++编写一个守护进程,它有一个简单的任务就是将一些事件插入到mysql数据库中。

当我运行top命令时,我看到进程的内存需求增加,我以为我有内存泄漏而且我开始使用Valgrind

我跑了valgrind:

  

valgrind --tool = memcheck --leak-check = yes --show-reachable = yes   --num-callers = 20 --track-fds = yes ./my_app

我收到以下报告:

==17045== 128 bytes in 1 blocks are definitely lost in loss record 6 of 11
==17045==    at 0x402A629: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==17045==    by 0x40AAB63: my_thread_init (in /usr/lib/i386-linux-gnu/libmysqlclient.so.18.0.0)
==17045==    by 0x40AAE43: my_thread_global_init (in /usr/lib/i386-linux-gnu/libmysqlclient.so.18.0.0)
==17045==    by 0x40A92D7: my_init (in /usr/lib/i386-linux-gnu/libmysqlclient.so.18.0.0)
==17045==    by 0x40863FA: mysql_server_init (in /usr/lib/i386-linux-gnu/libmysqlclient.so.18.0.0)
==17045==    by 0x4087B28: mysql_init (in /usr/lib/i386-linux-gnu/libmysqlclient.so.18.0.0)
==17045==    by 0x8049890: write_db(std::string, std::string, std::string) (Listener.cpp:76)
==17045==    by 0x804A692: SocketListener(void*) (Listener.cpp:182)
==17045==    by 0x4052D4B: start_thread (pthread_create.c:308)
==17045==    by 0x4582D3D: clone (clone.S:130)

函数write_db是这样的:

void write_db(std::string userid,std::string zona,std::string eveniment)
{
    try
    {
    MYSQL * connect;
    connect = mysql_init(NULL);
    connect = mysql_real_connect(connect,"127.0.0.1","myusr","mypwd","mytbl",0,NULL,0);
    std::string stmt = "INSERT INTO t_evenimente(placaid,codev,zona,cand) VALUES(\"" + userid + "\"," + eveniment + ",\"" + zona + "\",NOW())";
    std::cout << stmt << std::endl;
    mysql_query(connect,stmt.c_str());
    mysql_close(connect);
    std::cout << "Inserat eveniment obiectiv " << userid << std::endl;
    }
    catch (...)
    {
        std::cout <<"Exceptie MYSQL" << std::endl;
    }
}

内存泄漏在哪里?我正在使用mysql_init并关闭,因为文档说......这可能是误报吗?

2 个答案:

答案 0 :(得分:2)

由于您仅在函数内部使用connect,因此更容易不动态分配它并冒着内存泄漏的风险(很可能是您正在看到的那个)。此外,MySQL API是一个C API,并不会抛出任何异常,这将简化你现在所拥有的东西;

void write_db(std::string userid,std::string zona,std::string eveniment)
{
    MYSQL connect;
    mysql_init(&connect);
    mysql_real_connect(&connect,"127.0.0.1","myusr","mypwd","mytbl",0,NULL,0);
    std::string stmt = "INSERT INTO t_evenimente(placaid,codev,zona,cand) VALUES(\"" + userid + "\"," + eveniment + ",\"" + zona + "\",NOW())";
    std::cout << stmt << std::endl;
    mysql_query(&connect,stmt.c_str());
    mysql_close(&connect);
    std::cout << "Inserat eveniment obiectiv " << userid << std::endl;
}

当然,这仍然会遗漏错误处理,您需要将其添加回来。

答案 1 :(得分:1)

mysql_init返回需要由mysql_close释放的堆分配对象。如果mysql_init和mysql_close之间的某些内容抛出异常,则永远不会调用close。快速修复 - 将mysql_close添加到catch块。更好的解决方法 - 了解/使用RAII。

正如Angew指出的那样,当你调用mysql_real_connect时,你实际上可能更有可能泄漏连接(除非你在日志中看到你的异常文本)。您也可以使用RAII来避免这种情况。