Bug #88448 SQLExecDirect(hstmt, (SQLTCHAR*)"USE table;", SQL_NTS); leaks memorry upto 4Gb,
Submitted: 12 Nov 2017 3:47 Modified: 22 Nov 2017 10:47
Reporter: Nik Rayan Email Updates:
Status: Not a Bug Impact on me:
None 
Category:Connector / ODBC Severity:S3 (Non-critical)
Version:5.20.70 OS:Windows (10)
Assigned to: CPU Architecture:Any

[12 Nov 2017 3:47] Nik Rayan
Description:
Hi Guys,
Repeatedly executing USE %database% command leads to rapid increase of memory until it reach 4Gb and crashes. Any Idea why the following code has the issue?
btw: It seems a pretty valid code and database. 
To reproduce, please use valid table.
Nik

#include <windows.h>  
#include <sql.h>

int main()
{

	HENV    henv;
	HDBC    hdbc;

	SQLAllocEnv(&henv);
	SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
	SQLConnect(hdbc, (SQLTCHAR*)TEXT("1234"), SQL_NTS, (SQLTCHAR*)TEXT("1234"), SQL_NTS, (SQLTCHAR*)TEXT("1234"), SQL_NTS);

	while (true){

		HSTMT hstmt;
		SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
		SQLExecDirect(hstmt, (SQLTCHAR*)"USE database;", SQL_NTS);
		SQLFreeStmt(hstmt, SQL_CLOSE);
	}
}

How to repeat:
Modify the code below to enter your database details and a valid table, then run.
Check the memory usage. Once it reaches 4Gb, it crashes.

#include <windows.h>  
#include <sql.h>

int main()
{

	HENV    henv;
	HDBC    hdbc;

	SQLAllocEnv(&henv);
	SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
	SQLConnect(hdbc, (SQLTCHAR*)TEXT("1234"), SQL_NTS, (SQLTCHAR*)TEXT("1234"), SQL_NTS, (SQLTCHAR*)TEXT("1234"), SQL_NTS);

	while (true){

		HSTMT hstmt;
		SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
		SQLExecDirect(hstmt, (SQLTCHAR*)"USE ffmebeqxlcfzrikeyoqi;", SQL_NTS);
		SQLFreeStmt(hstmt, SQL_CLOSE);
	}
}

Suggested fix:
?
[22 Nov 2017 9:46] Bogdan Degtyariov
Hi Nik,

Thank you for your interest in MySQL software.
Your test program leaks memory because the statement is not freed.
Accordingly to ODBC API specification this function call only closes the cursor associated with the statement:

SQLFreeStmt(hstmt, SQL_CLOSE);

You can check here the meaning of SQL_CLOSE for SQLFreeStmt:
https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlfreestmt-function

To free the previously allocated STMT handle the parameter SQL_CLOSE has to be replaced by SQL_DROP:

SQLFreeStmt(hstmt, SQL_DROP);

After doing this simple change to your code the memory leak has stopped.
Therefore, I am closing this report with "Not a Bug" status.

Please feel free to reopen it at any time if the leak is still happening or you have more information about the problem.
Thanks.
[22 Nov 2017 10:47] Nik Rayan
Thanks!