sprintf() access violation reading location

-4

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);
c++
printf
access-violation
asked on Stack Overflow Sep 17, 2014 by MarioAda • edited Dec 15, 2017 by Vadim Kotov

1 Answer

0

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);
answered on Stack Overflow Sep 17, 2014 by MarioAda

User contributions licensed under CC BY-SA 3.0