我在一个使用大量MySQL查询的系统上工作,我遇到了一些内存问题,我很确定这与我没有正确处理指针有关……
基本上,我得到了这样的东西:
MYSQL_ROW function1() {
string query="SELECT * FROM table limit 1;";
MYSQL_ROW return_row;
mysql_init(&connection); // "connection" is a global variable
if (mysql_real_connect(&connection,HOST,USER,PASS,DB,0,NULL,0)){
if (mysql_query(&connection,query.c_str()))
cout << "Error: " << mysql_error(&connection);
else{
resp = mysql_store_result(&connection); //"resp" is also global
if (resp) return_row = mysql_fetch_row(resp);
mysql_free_result(resp);
}
mysql_close(&connection);
}else{
cout << "connection failed\n";
if (mysql_errno(&connection))
cout << "Error: " << mysql_errno(&connection) << " " << mysql_error(&connection);
}
return return_row;
}和function2()
MYSQL_ROW function2(MYSQL_ROW row) {
string query = "select * from table2 where code = '" + string(row[2]) + "'";
MYSQL_ROW retorno;
mysql_init(&connection);
if (mysql_real_connect(&connection,HOST,USER,PASS,DB,0,NULL,0)){
if (mysql_query(&connection,query.c_str()))
cout << "Error: " << mysql_error(&conexao);
else{
// My "debugging" shows me at this point `row[2]` is already fubar
resp = mysql_store_result(&connection);
if (resp) return_row = mysql_fetch_row(resp);
mysql_free_result(resp);
}
mysql_close(&connection);
}else{
cout << "connection failed\n";
if (mysql_errno(&connection))
cout << "Error : " << mysql_errno(&connection) << " " << mysql_error(&connection);
}
return return_row;
}main()基本上是一个无限循环,如下所示:
int main( int argc, char* args[] ){
MYSQL_ROW row = NULL;
while (1) {
row = function1();
if(row != NULL) function2(row);
}
}(变量和函数名已泛化,以保护无辜者)
但在第三次或第四次调用function2之后,只使用row进行读取,row开始丢失它的值,并出现段错误...
有人知道为什么吗?我不确定这段代码中的全局变量数量是否合适,但我并没有设计它,只能等到明天才能修复和完成它,所以欢迎使用变通方法!
谢谢!
发布于 2010-06-18 01:34:06
更新:我误解了mysql结果的使用方式。它看起来像是row指针数组指向您在function1()中释放的结果数组,然后在返回到堆之后在function2()中使用它。
您需要做的是在释放结果之前将return_row[2]复制到一个持久字符串。然后将其传递给function2()。我看到您在function2()中做了类似的事情,所以您也需要在那里修复它(尽管在您的示例中,您没有对它的返回值做任何事情)。
此外,您认为free(row);不是正确的做法,这一点是正确的。
发布于 2010-06-18 01:33:26
在处理mysql_fetch_row返回的行时,不应关闭连接或释放结果集。
https://stackoverflow.com/questions/3063834
复制相似问题