简体   繁体   中英

SQLite 3 statement preparation segfault

I'm using SQLite 3 in a C application of mine. It has worked like a charm up until now, when I've started to write unit tests. The function in question is a pretty small. It opens an in-memory database, prepares a statement and then does some stuff with it. Problem is that the app crashes with a segmentation fault at the sqlite3_prepare_v2 function call. I've tried to debug it and check to see that all arguments are valid, which they seem to be.

Below, I've pasted a minimal example which causes segfault in the same way. The backtrace lists sqlite3LockAndPrepare as the function where it crashes (called by sqlite3_prepare_v2 ).

As I mentioned above, I use SQLite without any problems in the rest of my app. I just can't figure out what the difference in usage is, since it's split up in several different routines which also does other stuff. The one thing I can spot is the use of an in-memory database instead of on-disk, but I tried with it on disk, and it made no difference.

#include <stdlib.h>
#include <stdio.h>
#include <sqlite3.h>

int main(void)
{
    sqlite3 *db;
    sqlite3_stmt **stmt;
    const char *str = "CREATE TABLE Test (t1 varchar(8) NOT NULL);";

    if (SQLITE_OK != sqlite3_open(":memory:", &db)) {
        printf("Can't open...\n");
        return 1;
    }

    sqlite3_prepare_v2(db, str, -1, stmt, NULL);

    return 0;
}

The fourth argument to sqlite3_prepare_v2() is supposed to be a valid pointer to an sqlite3_stmt * . You are instead passing an undefined value (since your variable stmt is never initialized). (Note, too, that even if that did not crash the program, you could not receive a pointer to the prepared statement that way.)

You should do this, instead:

int main(void)
{
    sqlite3 *db;
    sqlite3_stmt *stmt;
    const char *str = "CREATE TABLE Test (t1 varchar(8) NOT NULL);";

    /* ... create database ... */    

    sqlite3_prepare_v2(db, str, -1, &stmt, NULL);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM