1

我正在用 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 并按照文档所述关闭...这可能是误报吗?

4

2 回答 2

1

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

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

于 2013-02-06T07:54:33.953 回答
1

由于您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;
}

当然,这仍然忽略了错误处理,您需要将其添加回来。

于 2013-02-06T08:10:19.100 回答