SQLite3_step导致SEGFAULT

时间:2016-02-16 12:00:57

标签: c++ sqlite segmentation-fault

我正在尝试运行这段代码,但应用程序仍在最后一个sqlite3_step函数崩溃。当我在调试器下运行时,有时应用程序可以工作,但sqlite3_step会返回错误代码7(NOMEM)。

代码:

    string prereq("SELECT * FROM students WHERE KEYID=?;");
    sqlite3_stmt *stmt;
    const char* errmsg = nullptr;
    int res;
    res = sqlite3_prepare_v2(db,prereq.c_str(),prereq.size(),&stmt,&errmsg);
    sqlite3_bind_int64(stmt,1,sqlite3_int64(atoi(getID().c_str())));
    res = sqlite3_step(stmt);
    string req;
    switch (res)
    {
    case SQLITE_DONE:
        req += "INSERT ";
        break;
    case SQLITE_ROW:
        req += "UPDATE ";
        break;
    default:
        pmsg(errmsg,1);
        return -1;
        break;
    }
    sqlite3_reset(stmt);
    if(strcmp(req.c_str(),"INSERT ")==0)
        req += "INTO Students(KEYID,FNAME,LNAME,DOB,PHONE,ADDRESS,CITY,ZIP,COUNTRY,LVL,SECTION,GROUPS,ERRORLIST,ABSENCELIST,LUNCH,ACCESSRIGHT) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
    else req += "INTO students WHERE KEYID=? SET FNAME=?,LNAME=?,DOB=?,PHONE=?,ADDRESS=?,CITY=?,ZIP=?,COUNTRY=?,LVL=?,SECTION=?,GROUPS=?,ERRORLIST=?,ABSENCELIST=?,LUNCH=?,ACCESSRIGHT=?;";
    res = sqlite3_prepare_v2(db,req.c_str(),req.size(),&stmt,&errmsg);
    if(res!=SQLITE_OK) return -2;
    sqlite3_int64 keyid(atoi(getID().c_str()));
    sqlite3_bind_int64(stmt,1,keyid);
    sqlite3_bind_text(stmt,2,getFname().c_str(),getFname().size(),0);
    sqlite3_bind_text(stmt,3,getLname().c_str(),getLname().size(),0);
    sqlite3_bind_text(stmt,4,getDOB().c_str(),getDOB().size(),0);
    sqlite3_bind_text(stmt,5,getPhone().c_str(),getPhone().size(),0);
    sqlite3_bind_text(stmt,6,getAddress().c_str(),getAddress().size(),0);
    sqlite3_bind_text(stmt,7,getCity().c_str(),getCity().size(),0);
    sqlite3_bind_text(stmt,8,getZip().c_str(),getZip().size(),0);
    sqlite3_bind_text(stmt,9,getCountry().c_str(),getCountry().size(),0);
    sqlite3_bind_text(stmt,10,getLvl().c_str(),getLvl().size(),0);
    sqlite3_bind_text(stmt,11,getSection().c_str(),getSection().size(),0);
    string gp;
    for(string vgp: getGroups())
    {
        gp += vgp;
        gp += ";";
    }
    sqlite3_bind_text(stmt,12,gp.c_str(),gp.size(),0);
    sqlite3_bind_text(stmt,13,getErrors().c_str(),getErrors().size(),0);
    sqlite3_bind_text(stmt,14,getAbsences().c_str(),getAbsences().size(),0);
    sqlite3_bind_text(stmt,15,getLunch().c_str(),getLunch().size(),0);
    sqlite3_bind_text(stmt,16,getAR().c_str(),getAR().size(),0);
    res = sqlite3_step(stmt);
    cout << res << endl;
    if(res!=SQLITE_DONE) return -3;
    sqlite3_finalize(stmt);
    sqlite3_free(errmsg); 

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。我从更新请求中删除了“INTO”。我用strlen(funct())替换了funct()。size()。