I have a string which I want to break into a char[] array, is the
following way of doing this ok:
const char* test = new char[sQuery.length()];
Would this cause any issues or memory leaks?
You becha. And it probalby wouldn't do what you want anyway.
1. const char* test = new char[sQuery.length()];
You didn't allocate enough bytes. Since it's going to be a c-style string,
you need to add one more char for the null terminator.
2. you're making it const, so you can't change it.
char* test = new char[sQuery.length() + 1];
3. test = sQuery.c_str();
You are overwriting the pointer. You just lost the pointer to the memory
returned by new since you are now assigning it to the const char* reutrned
by c_str(). You need to copy the data, not the pointer. There is an old
c-function for this ( a number of them). strcpy (string copy).
strcpy( test, sQuery.c_str() );
Your delete[] test; is correct.
Incidently, there should be no reason to have to copy a std::string to a
cstyle string. If you have to copy it, copy the std::string.
I have found times I had to use a char[] instead of a std::string, and that
was because some cfunction copies into a char array and I can't really
provide that with std::string. I could with std::vector, but usually wind
up using char[] for this. I've not yet found any reason to have to copy
from a std::string to a char array though.