何时调用mysql_free_result(Resuing mysql_store_result,MYSQL_RES)

时间:2013-05-29 06:12:01

标签: c++ mysql memory-leaks

我有2个代码(程序)

计划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);
}

其他代码”涉及for循环,该循环调用使用相同res_set的函数来存储mysql_store_result的结果。 如图所示,我只在主要结束时拨打mysql_free_result(res_set);一次。

valgrind在上述情况下显示still reachable内存问题(我选择忽略)。没有其他泄漏。

计划2:

class mysqlClientClass具有以下私有变量

MYSQL *connect;
MYSQL_RES *res_set; 
MYSQL_ROW row;

有些方法(与我的问题相关),

mysqlClientClass::~mysqlClientClass()
{
if(connect!=NULL)
{   
    mysql_free_result(res_set);
    mysql_close(connect);   
}
}

如果用户未能调用closeConnection,析构函数将关闭它(通过检查connect是否设置为NULL或否)

void mysqlClientClass::closeConnection()
{
    mysql_free_result(res_set);
    mysql_close(connect);
    connect = NULL;
}

getResults是整个代码中使用mysql_store_result

的唯一方法
void mysqlClientClass::getResults(string iQuery)
{
 /* form query 
    execute Query */

res_set = mysql_store_result(connect);

 /* Do other things */

    mysql_free_result(res_set); // ------------------------>
    res_set = NULL;
    }
}

如果我没有释放函数末尾的res_set(并且只在析构函数/ close Connection中释放它)并且我多次调用这个函数valgrind报告,

=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)

这一切都归结为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)

根据mysql_store_result

manual页面
  

mysql_store_result()将查询的整个结果读取到客户端,   分配 MYSQL_RES结构,并将结果放入此结构中   结构

它还建议我在使用后拨打free_result

这似乎在程序2中有记载(当我不调用mysql_free_result时内存泄漏)但是为什么程序1没有显示任何泄漏?在程序1中,我在各个函数之间多次调用mysql_store_result,而不是每次都释放。

1 个答案:

答案 0 :(得分:-4)

您不需要mysql_store_result从查询中获取数据 - 使用sqlite3_exec的回调

int ListDataCallback(void *pArg, int argc, char **argv, char **columnNames){
  //cast pArg to your user data pointer
  //argc - count of columns in the result
  //argv - a result field as string

  return 0;
}

void get_data()
{
    char *selectErrMsgP = NULL;
    int err = sqlite3_exec( database, selectQ, ListDataCallback, (void*)myUserData, &selectErrMsgP );
    if( err ) {
        //handle error
    }
}

这种方法从来没有泄漏