Bug #67340 Memory leak in 5.2.2(w) ODBC driver causes Prepared_stmt_count to grow
Submitted: 23 Oct 2012 14:28 Modified: 20 Dec 2012 22:29
Reporter: Moises Soto Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / ODBC Severity:S3 (Non-critical)
Version:5.2.2(w) OS:Microsoft Windows (Windows 7 x64)
Assigned to: Bogdan Degtyariov CPU Architecture:Any

[23 Oct 2012 14:28] Moises Soto
Description:
After installing the new ODBC driver, while saving data to MySQL the ODBC driver generated the following error "Can't create more than max_prepared_stmt_count statements (current value: 16382)".  We opened MySWL Workbench and observed "Prepared_stmt_count" rise to its limit as our application saved the document to the database until it reached the limit, at which point we received the error.

We use prepared statements extensively in our application and wondering why they were not closed after calling:

SQLFreeStmt(hstmt, SQL_CLOSE);
SQLFreeStmt(hstmt, SWL_UNBIND);
SQLFreeStmt(hstmt, SQL_RESET_PARAMS);

How to repeat:
The following demonstrates how we prepare statements:

/* Declare variables */ 
...

SQLAllocStmt(hdbc, hstmt);

/* Prepare Statements */

SQLPrepare(hstmt, ..., SQL_NTS);

/* Bind Parameters */
...

SQLExecute(hstmt);

/* Free resources attached to statement */

SQLFreeStmt(hstmt, SQL_CLOSE);
SQLFreeStmt(hstmt, SWL_UNBIND);
SQLFreeStmt(hstmt, SQL_RESET_PARAMS);

/* Repeat process with the same statement */
...

Suggested fix:
We disabled Server-side prepared statements and the problem went away.  We would like to use the new feature but we can not figure out why the prepared statement count never decreases when we call SQLFreeStmt(...).
[26 Oct 2012 11:58] Bogdan Degtyariov
Thank you for reporting the problem.
In fact the driver is not only preparing new statement each time, but also has memory leak related to re-preparation.

The test case comes in the next post.
[26 Oct 2012 12:00] Bogdan Degtyariov
Test case

Attachment: bug67340.c (text/plain), 2.59 KiB.

[23 Nov 2012 12:34] Bogdan Degtyariov
Patch and test case

Attachment: bug67340.diff (application/octet-stream, text), 2.72 KiB.

[27 Nov 2012 5:55] Bogdan Degtyariov
The patch has been pushed to the source repository in revision 1099.
[20 Dec 2012 22:29] John Russell
Added to changelog for 5.2.3: 

An application making extensive use of prepared statements could
encounter an error:

Can't create more than max_prepared_stmt_count
statements (current value: 16382)

The issue occurred even if
SQLFreeStmt() calls were used. The Prepared_stmt_count value grew
until it exceeded the internal limit. A workaround was to disable
server-side prepared statements.