gpt4 book ai didi

c - SQLite3 中的内存泄漏

转载 作者:行者123 更新时间:2023-11-30 15:34:48 28 4
gpt4 key购买 nike

我们在以下函数中发现内存泄漏。如果我们将正确的消息作为函数的参数,SQL 查询将正确执行,并且内存保持不变。但如果消息中的字符为 ',那么(显然)执行失败,但内存开始增加。

int syslog_hwmod(unsigned short int type, unsigned short int err, const char *msg, const char *agent)
{
//Local variables:
int aux; //Auxiliary variable to check the returned errors of the functions.
unsigned int t0; //Current linux time in seconds.
char buffer[BUFFER_SIZE_LOG]; //Variable to write the SQL statement.
char *errMsg = 0; //Error message returned in the executing SQL statements.
sqlite3 *db; //Sqlite3 object that refers to the database connection.

//Initializing variables:
t0 = (unsigned int) time(NULL); //Save the current linux time in seconds.

//Open the syslog database connection:
aux = sqlite3_open(DB_PATH_SYSLOG, &db);
if(aux != SQLITE_OK) //Check the errors in the database connection.
return EGP0;

//Creates the SQL statement and executes it:
sprintf (buffer, "INSERT INTO syslog_hwmod VALUES (NULL,'%u','%hu','%hu','%s','%s');", t0,
type, err, msg, agent);
do{
aux = sqlite3_exec(db, buffer, NULL, NULL, &errMsg);

sqlite3_free(errMsg);

}while((aux == SQLITE_BUSY) || (aux == SQLITE_LOCKED)); //If the database is locked or busy,
//need to try again.

if(aux != SQLITE_OK) //Check the errors in the execution.
return EGP1;

//Close the syslog database connection:
sqlite3_close(db);

return NOERROR;
}

最佳答案

当发生错误时,该函数会在调用 sqlite3_close 之前中止执行。

当您分配了资源(例如打开的数据库)时,您必须确保这些资源始终被释放:

aux = sqlite3_open(DB_PATH_SYSLOG, &db);
if (aux != SQLITE_OK)
return EGP0;

...

sqlite3_close(db);

return aux != SQLITE_OK ? EGP1 : NOERROR;
<小时/>

请注意,可以使用 sqlite3_mprintf 正确格式化 SQL 字符串。 .

关于c - SQLite3 中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168319/

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