markmb
markmb

Reputation: 892

Memory Leakage in SQLite3

We have found a memory leak in the following function. If we put a correct message as parameter of the function, the SQL query is executed properly, and the memory stays constant. But if the message has characters as ', then (obviously) fails to execute, but the memory starts increasing.

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;
}

Upvotes: 0

Views: 1713

Answers (1)

CL.
CL.

Reputation: 180172

When an error happens, that function aborts execution before sqlite3_close is called.

Whan you have allocated resources (like the opened database), you must ensure that these resources are always freed:

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

...

sqlite3_close(db);

return aux != SQLITE_OK ? EGP1 : NOERROR;

Please note that it is possible to format SQL strings correctly with sqlite3_mprintf.

Upvotes: 1

Related Questions