Search code examples
csqlitedangling-pointer

SQLite SQLITE_STATIC Local Variable Issue


I am looking at some vendor code and there is a query like this:

BOOL BindQuery(sqlite3_stmt* stmt, PARAMS* params)
{
    char temp[150] = "";
    char paramBuf[10] = "";
    if (currStmt == NULL) return FALSE;

    sprintf(paramBuf, "%d", (int)params->someParam);
    strcpy(temp, "%");
    strcat(temp, tempVolt);
    strcat(temp, "%");
    sqlite3_bind_text(stmt, 4, temp, strlen(temp), SQLITE_STATIC);
    return TRUE;
}

Later down the road that query get executed. The problem is that this query never matches, even though it should.

I believe the problem is that sqlite3_bind_text binds a local variable and SQLite keep the pointer to the original local variable. So when it goes out of scope, it may have already been overwritten. The fix seems to be to use SQLITE_TRANSIENT instead. Can anyone confirm my thinking? Or am I off-base?

Another curious issue is that the vendor was never able to reproduce it. Luck?


Solution

  • Yes, this code is wrong. The documentation says:

    If the fifth argument is the special value SQLITE_STATIC, then SQLite assumes that the information is in static, unmanaged space

    but that local variable is not static.

    This code might work if that part of the stack happens to avoid being overwritten until the query is executed.