gpt4 book ai didi

c++ - C++ 程序的内存使用量增长,(在 Debian 的 "top"中显示),直到它崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:56 28 4
gpt4 key购买 nike

我正在开发一个C++程序,应该可以运行几天,所以它的内存消耗似乎增长得非常快,这有点麻烦。

程序的完整代码有点长,所以我只贴相关的东西。结构如下:

int main (void){
//initialization of the global variables
error = 0;
state = 0;
cycle = 0;
exportcycle = 0;
status = 0;
counter_temp_ctrl = 0;
start = 0;
stop = 0;


inittimer();
mysql_del ("TempMeas");
mysql_del ("TempMeasHist");
mysql_del ("MyControl");
mysql_del ("MyStatus");
initmysql();



while(1){

statemachine();

pause();

}

}

上面初始化的定时器函数如下:

void catch_alarm (int sig)
{
//Set the statemachine to state 1 (reading in new values)

start = readmysql("MyStatus", "Start", 0);
stop = readmysql("MyStatus", "Stop", 0);

if (start == 1){
state = 1;
}
if (stop == 1){
state = 5;
}


//printf("Alarm event\n");
signal (sig, catch_alarm);

return void();
}

所以基本上,由于我没有在修改 MyStatus 选项卡的 Web 界面中设置起始位,程序只是每秒调用 readmysql 函数两次(计时器的间隔)。 readmysql 函数如下:

float readmysql(string table, string row, int lastvalue){
float readdata = 0;

// Initialize a connection to MySQL
MYSQL_RES *mysql_res;
MYSQL_ROW mysqlrow;
MYSQL *con = mysql_init(NULL);
if(con == NULL)
{
error_exit(con);
}


if (mysql_real_connect(con, "localhost", "user1", "user1", "TempDB", 0, NULL, 0) == NULL)
{
error_exit(con);
}

if (lastvalue == 1){
string qu = "Select "+ row +" from "+ table +" AS a where MeasTime=(select MAX(MeasTime) from "+ table;
error = mysql_query(con, qu.c_str());
}
else{
string qu = "Select "+ row +" from "+ table;
error = mysql_query(con, qu.c_str());
}


mysql_res = mysql_store_result(con);

while((mysqlrow = mysql_fetch_row(mysql_res)) != NULL)
{
readdata = atoi(mysqlrow[0]);
}

//cout << "readdata "+table+ " "+row+" = " << readdata << endl;

// Close the MySQL connection
mysql_close(con);

//delete mysql_res;
//delete mysqlrow;


return readdata;
}

我认为这个函数中的变量存储在堆栈中,并在离开函数时自动释放。然而,似乎有一部分内存没有被释放,因为它毕竟只是在增长。如您所见,我已尝试对其中两个变量使用删除函数。好像没有效果。我在内存管理等方面做错了什么?

感谢您的帮助!

问候奥利弗。

最佳答案

至少 mysql_store_result 正在泄漏。来自 documentation :

After invoking mysql_query() or mysql_real_query(), you must call mysql_store_result() or mysql_use_result() for every statement that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, and so forth). You must also call mysql_free_result() after you are done with the result set.

关于c++ - C++ 程序的内存使用量增长,(在 Debian 的 "top"中显示),直到它崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38358669/

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