繁体   English   中英

C ++中的SQLite分段错误

[英]sqlite in c++ Segmentation fault

我想在我的数据库中设置一些记录,该代码将成功创建数据库和表,在函数“ addel”中,它将成功地将记录设置为数据库,但是当它想从“ ro”返回ro时,会出现“ Segmentation fault(core dumped)”错误addel”到主要...任何人都可以帮忙?

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <sqlite3.h>
#include <cstdio>

using namespace std;

void addel(sqlite3 * db);
void sqlmake(sqlite3 * db);
static int callback(void *NotUsed, int argc, char **argv, char **azColName);

void addel(sqlite3 * db) {
    string temps;
    int temp,x;
    char *cm;
    char *errm;

        x=sqlite3_open("12.db",&db);// open database because it closed before
    if(x) {
        cerr<<"can not creat database";
        exit(1);
    } else {
        cerr<<"open database successfully"<<endl;
    }

    cout<<"name : " ;
    cin>>temps;
    cout<<"age :" ;
    cin>>temp;

    sprintf(cm,"INSERT INTO pipl(ID,name) VALUES (%d,'%s');",temp,temps.c_str()); //creat sql query command
    x=sqlite3_exec(db,cm,callback,0,&errm);
    cout<< cm << endl;
    if(x!=SQLITE_OK) {
        cerr<<"error write record"<<errm<<endl;
        sqlite3_free(errm);
    } else
        cout<<"record written!" << endl;

    cout<<"done"<<endl;
        sqlite3_close(db);

}

//call back function to use for sqlite3_exec function
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

void sqlmake(sqlite3 * db) {
    int x;
    char *cm;
    char *errm;
    x=sqlite3_open("12.db",&db);
    if(x) {
        cerr<<"can not creat database";
        exit(1);
    } else {
        cerr<<"database created successfully"<<endl;
    }
    cm=(char *)"CREATE TABLE pipl(ID INT NOT NULL,name TEXT NOT NULL);";
    x=sqlite3_exec(db,cm,callback,0,&errm);
    if(x!=SQLITE_OK) {
        cerr<<"error bulding table"<<errm<<endl;
        sqlite3_free(errm);
    } else
        cout<<"table created";

    sqlite3_close(db);
    return ;
}

int main() {
    int x,x1;
    string temps;
    sqlite3 *db;
    sqlmake(db); //make database file and table in it
    addel(db); // add a record to table (problem)

    return 0;
}

您必须预订厘米的空间。 sprintf写一个缓冲区

char *cm 

仅创建一个指针,但不保留空间。

char cm[100]

sprintf可以预订100个字符的预订站点,将100更改为所需的空间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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