MySQL C API内存泄漏?

标签 mysql c api memory-leaks valgrind

最近,我开始编写一个使用 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/

相关文章:

mysql - 范围 IP 的远程 MySQL 连接

MySQL - 具有特定搜索值 'course' 的 FULLTEXT 搜索问题

java - 卡片布局 addLayoutComponent() API

android - 当我更改我的 api 级别时,我的 http 请求不起作用

java - MySQL 级联删除错误方向的更改(eclipselink 作为 JPA)

sql - 在 MySQL 中使用 JOINS

c++ - 只有在 header 中定义的函数才会被内联。我错过了什么吗?

c - Autoconf 问题 : “error: C compiler cannot create executables”

c - C高级题: Please explain C construct *({ foo(&bar); &bar; })

api - 验证用户的 API 凭据 - PayPal DoDirectPayment