Recently, I started to work on a C program that makes use of the libmysqlclient. When checking my code with valgrind, it reported memory leaks. The following minimal code snippet reproduces the behavior:
#include <mysql.h>
int main(void)
{
MYSQL* mysql = mysql_init(0);
mysql_close(mysql);
return 0;
}
Checking the resulting program with valgrind tells me:
==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
According to the MySQL API Reference, 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().
However, valgrind reports un-freed memory. What’s wrong here?
Digging through the docs, I found the function
mysql_library_end()that solves the issue.Citing from the MySQL API Reference:
On a personal note, I find it rather annoying that
libmysqlclientforces its users to call its own cleanup function. IMO, a nicer solution would be to callmysql_library_end()automatically whenever the connection count drops to zero.