gpt4 book ai didi

c++ - 函数返回 MYSQL_ROW

转载 作者:行者123 更新时间:2023-11-28 08:28:51 25 4
gpt4 key购买 nike

我在一个使用大量 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);
}
}

(变量和函数名称已被通用化以保护无辜者)

但是在第 3 次或第 4 次调用 function2 之后,它只使用 row 进行读取,row 开始失去它的值并出现段错误错误...

有人知道为什么吗?我不确定这段代码中的全局变量数量是否合适,但我没有设计它,直到明天才修复并完成它,所以欢迎解决方法!

谢谢!

最佳答案

更新:我误解了如何使用 mysql 结果。看起来 row 指针数组指向您在 function1() 中释放的结果数组,然后在它之后的 function2() 中使用它已经返回到堆中。

您需要做的是在释放结果之前将 return_row[2] 复制到一个永久字符串。然后将其传递给 function2()。我看到你在 function2() 中做了类似的事情,所以你也需要在那里修复它(尽管在你的例子中你没有对它的返回值做任何事情)。

此外,free(row); 不是正确的做法是正确的。

关于c++ - 函数返回 MYSQL_ROW,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3063834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com