mysql_free_result()在不同函数中调用mysql_store_result()时出现seg错误

时间:2014-06-10 17:05:47

标签: c++ mysql

我正在使用C ++进行编程,并希望将mysql_store_result()包装在一个以互斥锁围绕调用的函数中。当我调用mysql_free_result()时,这会导致段错误。如果我没有在函数中使用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();
}

1 个答案:

答案 0 :(得分:1)

我马上就看到了一个问题:

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调用,您的互斥锁将保持锁定状态。