我想在我的数据库中设置一些记录 此代码将成功创建数据库和表 并且在函数“addel”中它会成功地为数据库设置一条记录,但是当它想要从“addel”返回到main时会出现“Segmentation fault(core dumped)”错误... 任何人都可以帮忙吗?
#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;
}
答案 0 :(得分:1)
你必须预订cm的空间。 sprintf写一个缓冲区
char *cm
只创建一个指针,但不要预留空间。
char cm[100]
预订网站,其中sprintf可以写出100个字符,为期望的空间更改100个。