sprintf() access violation reading location - c++

I don't really understand this, here's what's going on:
char buffer1[100];
sprintf_s(buffer1, "whatever %s", "something");
Works just fine.
But the following doesn't:
char buffer1[100];
sprintf_s(buffer1, "whatever %s %s", "something", "somethingelse");
Error: Unhandled exception Access violation reading location 0x00000005.
I think if I try to split it up with strcpy_s first then use sprintf_s it would work but that would be a waste of everything.
Thanks in advance.
PS: I am using Visual Studio
EDIT:
Code Update, I wrote the wrong thing really fast. Here's the actual code that's giving the error:
sprintf(query, "INSERT INTO `members` (`id`, `username`, `email`) VALUES ('%s', '%s', '%s')", id, username, email);

The problem is that I was trying to append an integer to the char array using %s.
There's 2 solutions to the problem, it's wither you use %d or to_string to make the integer a string value which will fix the problem.
Solution 1:
sprintf(query, "INSERT INTO `members` (`id`, `username`, `email`) VALUES ('%d', '%s', '%s')", id, username, email);
Solution 2:
sprintf(query, "INSERT INTO `members` (`id`, `username`, `email`) VALUES ('%s', '%s', '%s')", to_string(id).c_str(), username, email);

Related

Adding data to SQLite through QT

I'm trying to make a registration form in Qt, I'm using SQLite database for this. When I run my program the compiler can open the database, however inserting info into this fails. I'm new to databases and will be very grateful if someone could help me to figure out what's the matter with it.
This is the part of my code about DB
database=QSqlDatabase::addDatabase("QSQLITE");
QString path = QFileDialog::getOpenFileName(0,"Open File","","DB files (*.sqlite) ;; All files (*)");
database.setDatabaseName(path);
if(database.open())
{
//creating a variable username
QString username;
//username equals to the input in the line editor
username= ui->usersname->text();
//creating a variable password
QString password ;
// password equals to the input in the line editor
password = ui->userspassword->text();
//creating a variable email
QString email;
//email equals to the input in the line editor
email = ui->usersemail->text();
//creating a variable phone number
QString phoneNumber ;
//phone number equals to the input in the line editor
phoneNumber= ui->usersphonenumber->text();
//running insert Query
QSqlQuery qry;
//put the info to the table created in the database
qry.prepare("INSERT INFO Users (Name, Password, Email, Phone)"
//select the values for inserting
"VALUES (:username, :password, :email, :phoneNumber)");
//binding values
qry.bindValue(":username", username);
qry.bindValue(":password", password);
qry.bindValue(":email", email);
qry.bindValue(":phoneNumber", phoneNumber);
//if adding info was successful
if(qry.exec())
{
//display a message box
QMessageBox::information(this, "Saved", "Your data was saved successfully, please log in");
}
//if adding info was not successful
else
{
QMessageBox::warning(this, "Failed", "Your data was not saved, please try again");
}
}
else
{
//display a warning message that the database was not connected
QMessageBox::warning(this,"Not Connected","The database is not connected");
}
C++ concatenates your query-string to:
INSERT INFO Users (Name, Password, Email, Phone)VALUES (:username, :password, :email, :phoneNumber)
The problem is that there is no space-character between "[...]Phone)" and "VALUES[...]".
This leads to the VALUES keyword cannot be parsed correctly.
To fix this, just place a space-character at the beginning of the second query-string-part like this:
//select the values for inserting
" VALUES (:username, :password, :email, :phoneNumber)");

Qt Parameter Count Mismatch with QSQL and Bind Values

I'm currently facing an error where I get "Parameter count mismatch" from query.lastError, my bindvalues are correct (i've tested them).
My query is:
QSqlQuery query(DBT);
query.prepare("SELECT Foto, Nombre, Apellido1, Apellido2, Curso, Grupo, FotoHuella FROM usuarios WHERE Nombre=:nombre1 OR Apellido1=:apellido1 OR Apellido2=:apellido2 OR Curso=:curso1 OR Grupo=:grupo1");
query.bindValue(":nombre1", nombre, QSql::Out);
query.bindValue(":apellido1", apellido1, QSql::Out);
query.bindValue(":apellido2", apellido2, QSql::Out);
query.bindValue(":curso1", curso, QSql::Out);
query.bindValue(":grupo1", grupo, QSql::Out);
query.exec();
In case you where wondering here is where I set up the database:
QSqlDatabase DBT=QSqlDatabase::addDatabase("QSQLITE");
DBT.setDatabaseName("/home/pi/FoodCircleDBT.db");
DBT.open();
Thanks in advance.
Solution for me: actually everything relating to the code worked perfectly but somehow my database schema went crazy when I edited it with a database program. So If you are facing this I recommend you to open the command line and checking your schema.

Correct usage of sqllite3_bin_text

I'am writing a small application (Login Mask) to get comfortable with the usage of SQLite3.
Right now I have a problem with the correct usage of sqlite3_bind_text(). I've create a small DB with only 1 row. In this part of the code I would like to bind the user input to a variable and bind it to a statement. The user input delivered is by the getline(cin,variable) function.
My problem:
I get an instant "False Library use" when I try to use the bind method. The result is always 21. I have read the API documentation several times, but I obviously don't understand the last part.
Can someone please show me how to correctly use this function(s)?
I've checked my column types and they are "Text NOT NULL".
int Login::check_login(string username, string password) {
int errcode = 0;
string query = "Select a_username,a_password from t_user where a_username = ? and a_password = ?;";
sqlite3_stmt *createStmt;
errcode = sqlite3_prepare_v2(datab->get_db(), query.c_str(), query.size(), &createStmt, NULL);
if (!errcode)
throw runtime_error("Failed! Can not prepare statement DB.");
errcode = sqlite3_bind_text(createStmt, 1, password.c_str(), -1, SQLITE_STATIC); // Always 21 because of false library use
//there is more code but i think this should be enough
P.S.
I've googled this 2 days and found no solution / easy explanation of my problem.
I think your call to sqlite3_prepare_v2() fails and doesn't prepare valid statement (you don't get exception, don't you?), but there is a typo in error check.
When sqlite3_* function succeeds, it returns SQLITE_OK which is 0. So correct error check is:
if (errcode)
throw runtime_error("Failed! Can not prepare statement DB.");
That is why sqlite3_bind_text() also fails.

MD4 hashing with Crypto++ results in wrong hash?

I'm using Crypto++ to generate a MD4-Hash from a given password. But the generated hash doesn't seem to be correct. I think I'm misusing the CryptoPP functions somewhere.
CryptoPP::Weak1::MD4 hash2;
byte digest2[CryptoPP::Weak1::MD4::DIGESTSIZE];
hash.CalculateDigest(digest2, (byte*)password, strlen(password));
CryptoPP::HexEncoder encoder2;
std::string output2;
encoder2.Attach(new CryptoPP::StringSink(output2));
encoder2.Put(digest,sizeof(digest2));
encoder2.MessageEnd();
printf("END %s \n", output2.c_str());
My variable password contains the value "test". The printed output is:
END 3CC942AE509EC070B2548515E00F8CE8
The expected value, tested by some MD4 Hash Generators, is:
db346d691d7acc4dc2625db19f9e3f52
Any ideas?
Okay, I found the solution by myself. It doesn't work the way I posted above.
Here the correct code, it may be useful for someone else:
std::string value;
CryptoPP::Weak1::MD4 hashmd4;
CryptoPP::StringSource (password, true,
new CryptoPP::HashFilter( hashmd4,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(value)
)
)
);
hash.CalculateDigest(digest2, (byte*)password, strlen(password));
This should be:
hash2.CalculateDigest(digest2, (byte*)password, strlen(password));
That is, hash2, not hash.
encoder2.Put(digest,sizeof(digest2));
This should be:
encoder2.Put(digest2,sizeof(digest2));
That is, digest2, not digest.
The expected value, tested by some MD4 Hash Generators, is:
db346d691d7acc4dc2625db19f9e3f52
Yep, that's what I get using the code you posted after the typos were fixed.

unable to print string value using sprintf in c++

i have function that takes two parameters of type LPTSTR, and i am trying print both the values using sprintf like below and i am not able to print the exact values.
int __stdcall Logon(LPTSTR UserName, LPTSTR Password)
{
char Buffer[2048];
sprintf(Buffer,"UserName: %s\n m_Password: %s\n",UserName,Password);
FILE *Ls=fopen("lo.log",a);
fprintf(Ls,Buffer);
fclose(Ls);
}
Either fix "Use Unicode strings" in you project settings or use the
_stprintf(Buffer, _T("UserName: %S\n m_Password: %S\n"), UserName, Password);
and
#include <tchar.h>
If you use Unicode (and you do), use the '%S' format.
Assuming that UserName and Password are stored as wide strings (wchar_t) and you are trying to put them into a char[] buffer, then visual c++ uses %S to accomplish this.
sprintf(Buffer,"UserName: %S\n m_Password: %S\n",UserName,Password);