我正在用C++编程,并希望将mysql_store_result()封装在一个函数中,这个函数围绕着互斥对象的调用。当我调用mysql_free_result()时,这会导致seg错误。如果函数中没有mysql_store_result(),只需将其封装在互斥对象中,它就能正常工作。
void getList() {
if (query == SUCCESS) {
MYSQL_RES *res_set;
//MySQLStoreResult(res_set);
// If I uncomment the line above the program set faults below.
// If I uncomment the lines below the program works fine.
/*mutex.lock();
res_set = mysql_store_result(mysql);
mutex.unlock();*/
unsigned int num_rows = mysql_num_rows(res_set);
if (num_rows > 0) {
//loop through all the rows using mysql_fetch_rows()
mysql_free_result(res_set); // seg fault
}
}
}
void MySQLStoreResult(MYSQL_RES *res_set) {
mutex.lock();
res_set = mysql_store_result(mysql);
mutex.unlock();
}发布于 2014-06-10 17:47:34
我现在看到一个问题:
void MySQLStoreResult(MYSQL_RES *res_set) {
mutex.lock();
res_set = mysql_store_result(mysql);
mutex.unlock();
}该res_set指针是该函数的本地指针。当您返回到调用方时,您不会看到这些更改。因此,在调用代码中,您使用的是未初始化的指针。
这一职能应该是:
void MySQLStoreResult(MYSQL_RES *& res_set) {
mutex.lock();
res_set = mysql_store_result(mysql);
mutex.unlock();
}必须传递对指针的引用。
另外,您应该使用RAII同步对象。如果您将mysql_store_result()更改为可以throw的函数,或者添加更多可以throw的代码,该怎么办?您的互斥锁将保持锁定,因为unlock调用从未被执行。
https://stackoverflow.com/questions/24146943
复制相似问题