Reputation: 5917
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?
Upvotes: 5
Views: 2492
Reputation: 5917
Digging through the docs, I found the function mysql_library_end()
that solves the issue.
Citing from the MySQL API Reference:
This function finalizes the MySQL library. You should call it when you are done using the library (for example, after disconnecting from the server).
On a personal note, I find it rather annoying that libmysqlclient
forces its users to call its own cleanup function. IMO, a nicer solution would be to call mysql_library_end()
automatically whenever the connection count drops to zero.
Upvotes: 8