Originally Posted by
xwielder
Would you agree this be the best solution?
No, it is unnecessarily complex. The point of using std::string here is so that you don't have to do manual memory management.
Originally Posted by
xwielder
The program constantly crashes when I use single quotes. (Seems to break on malloc.c "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src\malloc.c" on line 55, which is this:
The reason is simple: you pretty much ignored what I wrote in post #6. When I posted my example in post #9, I was working on the assumption that my earlier example in post #4 mixed up the parameters, hence the compile error that you alluded to, so I should reverse the order. I was wrong, but you failed to check.
In fact, I was wrong on 3 counts:
- std::string does not have a constructor that takes a single parameter of integer type.
- std::string does have a constructor that takes two parameters, with exactly what I had in mind in post #2, so reversing the order is wrong.
- Mixing up the order would not result in a compile error, which is precisely the problem you experienced later.
Consequently, this should be correct:
Code:
std::string sql(const char* dataIn)
{
std::size_t dataInLen = strlen(dataIn);
std::string to(dataInLen * 2 + 1, '\0');
mysql_real_escape_string(MySQL_Database_Connection__global, &to[0], dataIn, dataInLen);
return to;
}
That said, note that at the moment, the &to[0] trick is not guaranteed by the standard to result in a pointer to the first element of a contiguous sequence of characters. However, it will be guaranteed later this year, and your standard library implementation probably does it that way.