I want to implement a function of regular reconnection after a failed database connection, but I don"t know why there is a memory leak, so I"d like to ask the gods.
to make it easier to ask questions, I tidied up the code, connected to the database directly in an endless loop, and then disconnected the database to release resources. After the program runs, by observing the task manager, you can find that the memory is increasing all the time.
at present, it is found that some memory will be applied for after the SQLDisconnect function is executed, but it doesn"t seem to be freed, but this is because the system API, can"t see the source code, so I"m not sure if this is the problem.
the following is the code I have streamlined:
-sharpinclude <windows.h>
-sharpinclude <sql.h>
-sharpinclude <sqlext.h>
-sharpinclude <string>
-sharpinclude <iostream>
int main() {
std::string connectString("filedsn=c:\\mssql.dsn");
while(true)
{
SQLRETURN retCode;
SQLCHAR connStrbuffer[1024];
SQLSMALLINT connStrBufferLen;
SQLHENV henv = NULL; // Environment
SQLHDBC hdbc = NULL; // Connection handle
SQLHSTMT hstmt = NULL; // Statement handle
retCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
retCode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, -1);
retCode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
retCode = SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)10, 0);\
retCode = SQLDriverConnect(hdbc, NULL, (SQLCHAR *) connectString.c_str(),
(SQLSMALLINT)connectString.size(), connStrbuffer, 1025, &connStrBufferLen, SQL_DRIVER_COMPLETE);
retCode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
if (hstmt) {
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
hstmt = NULL;
}
if (hdbc) {
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
hdbc = NULL;
}
if (henv) {
SQLFreeHandle(SQL_HANDLE_ENV, henv);
henv = NULL;
}
}
return 0;
}
mssql.dsn information is as follows:
[ODBC]
DRIVER=SQL Server
UID=sa
DATABASE=termsec2
SERVER=192.168.1.156
PORT=1433
PWD=123456