簡體   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