I have 2 codes (programs)
Program 1:
//global variables MYSQL_RES *res_set; MYSQL_ROW row; MYSQL *connect; int main() { connect=mysql_init(NULL); mysql_real_connect(connect, NULL, "root", "suvp" ,"Employees" ,0,NULL,0); /*Other Code*/ mysql_free_result(res_set); mysql_close(connect); }
“ Other code ” includes a for loop that calls functions that use the same res_set to store the results from mysql_store_result . As you can see, I call mysql_free_result(res_set); only once at the end of main.
valgrind shows memory problems still reachable in the above case (which I decided to ignore). There are no other leaks.
Program 2:
The mysqlClientClass class has the following private variables,
MYSQL *connect; MYSQL_RES *res_set; MYSQL_ROW row;
Some of the methods (relate to my problem)
mysqlClientClass::~mysqlClientClass() { if(connect!=NULL) { mysql_free_result(res_set); mysql_close(connect); } }
If the user cannot call closeConnection , the destructor will close it (if it is established that the connect parameter is set to NULL or not)
void mysqlClientClass::closeConnection() { mysql_free_result(res_set); mysql_close(connect); connect = NULL; }
getResults is the only method in all code that uses mysql_store_result
void mysqlClientClass::getResults(string iQuery) { res_set = mysql_store_result(connect); mysql_free_result(res_set);
If I do not release res_set at the end of the function (and release it only in the / close Connection destructor), and I make several calls to this function valgrind reports,
=10162== LEAK SUMMARY: ==10162== definitely lost: 312 bytes in 3 blocks ==10162== indirectly lost: 49,152 bytes in 9 blocks ==10162== possibly lost: 0 bytes in 0 blocks ==10162== still reachable: 73,872 bytes in 21 blocks ==10162== suppressed: 0 bytes in 0 blocks ==10162== Reachable blocks (those to which a pointer was found) are not shown. ==10162== To see them, rerun with: --leak-check=full --show-reachable=yes ==10162== ==10162== For counts of detected and suppressed errors, rerun with: -v ==10162== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
and it all comes down to mysql_store_result
==10162== by 0x406C3CA: mysql_store_result (in /usr/lib/i386-linux-gnu/libmysqlclient.so.18.0.0) ==10162== by 0x8048E03: mysqlClientClass::getResults(std::string) (mysqlClientClass.cpp:103)
According to the manual, mysql_store_result page
mysql_store_result () reads the entire query result to the client, allocates the MYSQL_RES structure and puts the result in this structure.
and he also offers me to call free_result after use.
This seems to work as described in program 2 (memory leak when I don't call mysql_free_result ), but then why does program 1 not show any leaks? In program 1, too, I make several calls to mysql_store_result between different functions without releasing each time.