Bug #60431 Free resources on unload
Submitted: 11 Mar 2011 12:26 Modified: 24 Feb 2012 9:22
Reporter: Peter Christensen Email Updates:
Status: Not a Bug Impact on me:
None 
Category:MySQL Server: C API (client library) Severity:S4 (Feature request)
Version:5.1.56 OS:Linux
Assigned to: CPU Architecture:Any
Tags: gcc, Leak, my_end, mysql_library_end, PAM

[11 Mar 2011 12:26] Peter Christensen
Description:
Currently, in order to free up all allocations done by libmysqlclient, you'll have to manually call mysql_library_end(), but if libmysqlclient is for some reason unloaded, the memory never gets freed.

In the Windows-version I've noticed that DllMain has been used to actually enforce a call to my_end() when the library is finally unloaded. The same could be done for at least Linux when compiled with gcc. (Looks like this has been removed from MySQL 5.5?)

The place where I found the "hack" useful is when using libpam-mysql with an application. Should libpam-mysql call mysql_library_end() when it is unloaded? The host application doesn't know whether using PAM will eventually use MySQL, nor does the library know if the application used MySQL. If libpam-mysql calls mysql_library_end() on unload, it potentially frees up resources necessary for the application, but if it doesn't and the application did not use MySQL, a memory leak occurs because PAM will load and unload libpam-mysql each time PAM is used.

How to repeat:
Load and unload a module which uses MySQL, but doesn't call mysql_library_end

Suggested fix:
Add something like to a unix.c or similar under libmysql

#if defined(__GNUC__) && !defined(WINDOWS) && !defined(__WIN__)

__attribute__((destructor)) void libmysql_free(void)
{
  my_end(0);
}

#endif
[24 Feb 2012 9:22] Georgi Kodinov
Automatic initialization of mysql durring dll/shared object library  load/unload is a double-edged sword.  See http://lists.mysql.com/commits/53011 for reference.
You will need to find some other ways to initialize libmysql in your application.