最近,我开始编写一个使用 libmysqlclient
的 C 程序。使用 valgrind
检查我的代码时,它报告内存泄漏。以下最小代码片段重现了该行为:
#include <mysql.h>
int main(void)
{
MYSQL* mysql = mysql_init(0);
mysql_close(mysql);
return 0;
}
用 valgrind
检查生成的程序告诉我:
==25614== LEAK SUMMARY:
==25614== definitely lost: 0 bytes in 0 blocks
==25614== indirectly lost: 0 bytes in 0 blocks
==25614== possibly lost: 0 bytes in 0 blocks
==25614== still reachable: 288 bytes in 3 blocks
==25614== suppressed: 0 bytes in 0 blocks
根据 MySQL API 引用,mysql_close()
...
Closes a previously opened connection. mysql_close() also deallocates the connection handle pointed to by mysql if the handle was allocated automatically by mysql_init() or mysql_connect().
但是,valgrind
报告未释放的内存。这里有什么问题吗?
最佳答案
通过深入研究文档,我找到了解决问题的函数 mysql_library_end()
。
引自 MySQL API 引用:
This function finalizes the MySQL library. You should call it when you are done using the library (for example, after disconnecting from the server).
就我个人而言,我发现 libmysqlclient
强制其用户调用其自己的清理函数非常烦人。 IMO,一个更好的解决方案是在连接计数降为零时自动调用 mysql_library_end()
。
关于MySQL C API内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8554585/