On 21 Jul, 02:03, "Jim Langston" <tazmas...@rocketmail.comwrote:
Quote:
"Paul" <Gef.Mongo...@gmail.comwrote in message
>
news:1184942647.508494.272260@d55g2000hsg.googlegr oups.com...
>
>
Quote:
I have a string which I want to break into a char[] array, is the
following way of doing this ok:
>
Quote:
const char* test = new char[sQuery.length()];
>
Quote:
test = sQuery.c_str();
>
>
>
Quote:
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.
Thanks for the replies all. I was using char[] as I needed to parse
the string on a character basis. The string would be a query from a
search page and it could contain words or phrases sorrounded by speech
marks or contain other tokens such as: + - etc So this seemed the best
way to do it: Firstly parse the string on a character basis through a
small algorithm which would break it into tokens based upon their
placement, open/closed speech marks etc, then place the tokens into a
collection as strings, which was looped through to generate part of a
large SQL query.
The reason for using const char* was because the compiler was throwing
up errors on this line of code: test = sQuery.c_str();, saying it
couldnt convert a char to a const char.
It compiled and worked, but I was worried about memory leaks etc, and
from all your answers, it seems I was right to do so. Thanks again :).