Bug #27402 ODBC Handle Leak
Submitted: 23 Mar 2007 15:36 Modified: 3 Sep 2007 14:48
Reporter: Marcus Kruse Email Updates:
Status: Duplicate Impact on me:
None 
Category:Connector / ODBC Severity:S2 (Serious)
Version:3.51.14 OS:Windows (Windows XP SP2)
Assigned to: CPU Architecture:Any

[23 Mar 2007 15:36] Marcus Kruse
Description:
I get a handle leak when connecting/disconnecting to a mysql db (version 5.0.24a) in a multithreaded environment.

How to repeat:
Compile this code as a multithreaded console application.
The output will show the total number of connections (to be compared against the total handle count in the task manager).
Since every connection is disconnected and all handles are closed there should be no handle increase. but there is...

#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

#define DSN	"TestDB"
#define USER	"test"
#define PASS	"password"

#define SPAWN	99

int main(int argc)
{
	static int count=0;
	SQLHENV henv;
	SQLHDBC hdbc;

	if (argc!=SPAWN) {

		// spawn off 9 threads...
		for (argc=0;argc<9;argc++)
			CreateThread(0, 0, (LPTHREAD_START_ROUTINE)main, (LPVOID)SPAWN, 0, 0);
	}

	// connect and disconnect until the system runs out of handles...
	for (;;) {

		henv=SQL_NULL_HENV;
		hdbc=SQL_NULL_HDBC;

		if (SQLAllocHandle(SQL_HANDLE_ENV,NULL, &henv) == SQL_SUCCESS
			&& SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER) == SQL_SUCCESS
			&& SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc) == SQL_SUCCESS
			&& SQLConnect(hdbc, DSN, SQL_NTS, USER, SQL_NTS,PASS, SQL_NTS) == SQL_SUCCESS) {
				printf("%08X: count = %d\r\n",GetCurrentThreadId(),++count);
				SQLDisconnect(hdbc);
		}
		else
			printf("ODBC error %d\r\n",GetLastError());

		if (hdbc != SQL_NULL_HDBC)
			SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
		if (henv != SQL_NULL_HENV)
			SQLFreeHandle(SQL_HANDLE_ENV, henv);

		Sleep(1000);
	}

	return 0;
}
[11 Apr 2007 8:30] Tonci Grgin
Hi Marcus and thanks for excellent report.

It do really appear that we're loosing handles, precisely environment handles, but I will have to investigate this more since general query log shows mess that shouldn't be there.

Thanks for your interest in MySQL!
[11 Apr 2007 10:15] Tonci Grgin
Verified as described.
[12 Apr 2007 11:45] Bogdan Degtyariov
Marcus,

Is MyODBC 3.51.14 from our GA release or from some pre-release build?
Thanks.
[12 Apr 2007 14:45] Marcus Kruse
It's the GA release (http://dev.mysql.com/get/Downloads/MyODBC3/mysql-connector-odbc-3.51.14-win32.msi/from/htt...)
having MD5: e49ffdf58a14793d584dd5b0595b02e3
[3 Sep 2007 14:48] Tonci Grgin
This is a duplicate of Bug#21385.
[3 Sep 2007 14:51] Tonci Grgin
Possibly related to Bug#14283: Handle leak when Sleep() under multithread, marked as !Bg by Miguel.