The Bluff
The Bluff

Reputation: 91

SQLite3_step cause SEGFAULT

I am trying to run this piece of code but the app still crash on the last sqlite3_step function. When I run under the debugger, sometimes the app works but sqlite3_step return the error code 7 (NOMEM).

CODE :

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

Upvotes: 0

Views: 623

Answers (1)

The Bluff
The Bluff

Reputation: 91

I found the solution to my problem. I removed the "INTO" from the update request. I replaced the funct().size() by strlen(funct()).

Upvotes: 0

Related Questions