Reputation: 35
i want to set some record to my database this code will create database and table successfully and in function "addel" it will set a record to database successfully but it give "Segmentation fault (core dumped) " error when it want ro return from "addel" to main ... any one can help ?
#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;
}
Upvotes: 1
Views: 2162
Reputation: 367
You have to book space for cm. sprintf writes a buffer
char *cm
only creates a pointer but don't reserve space.
char cm[100]
booking site where sprintf can write 100 characters, change 100 for desired space.
Upvotes: 1