SQLite3中的内存泄漏

时间:2014-04-19 09:29:11

标签: c memory-leaks sqlite

我们在以下函数中发现了内存泄漏。如果我们将正确的消息作为函数的参数,则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;
}

1 个答案:

答案 0 :(得分:1)

发生错误时,该函数会在调用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字符串。