Archived

This topic is now archived and is closed to further replies.

why not to use char * for strings?

This topic is 5178 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

people are saying not to use char * for a string. How come? eg char * myString; or char * myMethod() { return "hi"; } And why not use LPSTR instead of std::string as the second one doesnt work with methods...? [edited by - johnnyBravo on October 14, 2003 7:55:25 AM]

Share this post


Link to post
Share on other sites
Because you need to (de)allocate memory for the strings yourself if they''re char pointers. And you can''t use operators to concatenate or copy strings. These together account to ugly code with lots of potential bugs, since you''ll forget to (de)allocate memory anyway.

Share this post


Link to post
Share on other sites
I''ll answer the 2nd question first. LPCSTR is Windows-specific. I haven''t done much windows programming, but won''t functions that accept LPCSTR accept a null-terminated C string? If so, you can use std::string::c_str().

Why use std::string instead of char *? You can eliminate a large class of memory problems by doing so. For static data, it''s not so much of an issue:

const char * PROG_NAME = "MyProgram";

But for variable length strings, I''d rather let std::string handle the memory management and resizing.

--
Dave Mikesell
d.mikesell@computer.org
http://davemikesell.com

Share this post


Link to post
Share on other sites
Don''t listen to what people tell you, only use strings where you need them, eg you manipulate the string or such, and don''t use them as arguments for any type of interface that you want to maintain any binary compatibility for, or want to use from another language.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by johnnyBravo
char * myMethod()
{
return "hi";
}


Doesn''t that give you a memory error? If not, it''s probably more luck than anything else. Anyway, having a function return a pointer to a local variable that''s popped from the stack when the function exits, is one of the Two Mortal Sins of C programming (the other one is to malloc() without free()). Even if it works in this case, it''s still a really bad habit.
quote:

And why not use LPSTR instead of std::string as the second one doesnt work with methods...?


What? Of course std::string works with methods. Why wouldn''t it?

Share this post


Link to post
Share on other sites
I myself like to use char* instead of std::string.

Firstly its faster;
Secondly I'm comfortble with it; and
Thirdly even though I know I have to manage the memory for it, it keeps me from slacking off into the lazy chair and I know exactly whats going on.

Sure the std::string is comfortable to work with and does everything for you but if you have an array that is supposed to hold about 10,000 strings, then you are wasting a lot of RAM!

Well this topic depends on how well you know c-strings and for what purpose.

I'm not going to force you to use c-pointers but know that some time you are going to use it (or have to use it) and for that you need to know how it works.


// Last Attacker \\---=( LA )=---// LA Extreme \\

ICQ Number : 120585863

E-mail: laextr@icqmail.com

[edited by - Last Attacker on October 14, 2003 8:49:14 AM]

Share this post


Link to post
Share on other sites
AnonymousPoster brought up a good point about interfacing with other languages. That''s something to consider.

As with every decision, there are tradeoffs with each option. You have to choose which is best for your program.

--
Dave Mikesell
d.mikesell@computer.org
http://davemikesell.com

Share this post


Link to post
Share on other sites
People usually say use std::string becuase they assume you''re too damn retarded to deal with memory yourself.

Remember that std::string is a reasonably lightweight way to have a more or less nice string class. Sometimes it''s appropriate, and sometimes it''s not. Occasionally I''ll just create a 500char array and mess with it if I''m feeling lazy, and I nearly always use char* return types rather than std::string. Especially for DLL type stuff, where it''s conceivable that other languages might actually want to access the stuff.

LPSTR is something like this:
typedef char* LPSTR;
You probably won''t find that exact line in the windows headers, but when you hack through it all, that''s what you get. It''s nothing special.

As long as you can handle memory well, there''s nothing wrong with char*. I usually use std::string in places I don''t want to have explicit deletion, e.g. as a member of a struct that has a string in it, but for which i don''t want to write a destructor. std::string also has its nice concatenation operator, if you like that sort of thing.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Last Attacker
Sure the std::string is comfortable to work with and does everything for you but if you have an array that is supposed to hold about 10,000 strings, then you are wasting a lot of RAM!


Not really, not if you''re reasonably careful. That is, don''t force std::string to reallocate more than nessecary. Use reserve() and some good judgement.

IMHO char* is fine for constant strings, but when dealing with variable-sized strings, std::string is far superior on all possible levels. realloc() anyone? (*shudder*).

Share this post


Link to post
Share on other sites
As with all things in programming its a matter of the right tool for the right job, sometimes using a char * is needed, others you can use std::string.

Personaly i tend towards std::string as it saves me having to write string manip stuff myself and its just natural to use when using the rest of the STL.

Share this post


Link to post
Share on other sites
Hello johnnyBravo,

use of const char* is alright to do for any "string" in C/C++
or char* if your allocating a buffer to do something with like copy data into it and sending over socket.
We have a multi-threaded app that takes care of sending data over socket so we just pass it a buffer and size of buffer and when it done sending it deletes the buffer.

Else if your going to do things with the string then like the others point out std:string is alright to use and should be use as much as possible. But I would advise a few rules.
1) try not to past a std::string by value always do it by reference.
2) try to avoid return of a string.

This will avoid a lot of temp strings and copy memory.

in example:
very efficient
void myMethod(string & t)
{
t = "Hi";
}
next is retun a sting of the temp string.
creates a stack sting on stack allocating memory for "Hi"
then returns this which involves creating another temp string
then copies memory form stack to the temp string
then copies form this temp string to the sting being assigned.
string myMethod();
{
string stack("Hi"); //create on stack
return stack; // has to create a temp sting and copy stack data into it
}

Note most compiler tempory return object stay around until end of block ie. closing }
But I would always use the myMethod with pass in reference my self.
it cleaner code and no mem copies and no temp string do to return of a string.

Lord Bart




[edited by - lord bart on October 14, 2003 9:50:51 AM]

Share this post


Link to post
Share on other sites
As I've already said many times before, the conversion to a char* is deprecated, as stated by the standard. That is, use const char*.

[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on October 14, 2003 11:03:31 AM]

Share this post


Link to post
Share on other sites
Thanks alot on all the insight, it has cleared things up for me.
quote:
Original post by Lord Bart
2) try to avoid return of a string.



[edited by - lord bart on October 14, 2003 9:50:51 AM]



About the avoiding return of a string,
i didnt realise this until you described it in that sense,

like i had a read method for reading text files.
And i made it return a string instead of using references.

I think i''ll change it back to using references

Im just use to using vb where most things return stuff

Share this post


Link to post
Share on other sites
quote:
Original post by Last Attacker
I myself like to use char* instead of std::string.

Firstly its faster;

Except when it isn''t, of course.

quote:
Secondly I''m comfortble with it; and
Thirdly even though I know I have to manage the memory for it, it keeps me from slacking off into the lazy chair and I know exactly whats going on.

Bollocks. Most people are too busy with actually writing applications to bother with allocating memory for strings.

quote:
Sure the std::string is comfortable to work with and does everything for you but if you have an array that is supposed to hold about 10,000 strings, then you are wasting a lot of RAM!

You''re "wasting" perhaps 16 bytes per string. That hardly constitutes a "lot" of RAM.

Share this post


Link to post
Share on other sites

As with all things, "It depends" is the best answer.

I assume you are aware that the ''char'' datatype isn''t guaranteed to be eight bits in size from platform to platform. If you ever want to work with multi-byte character sets, such as Unicode, you could find that your prized, hand-rolled string manipulator code falls to pieces.

Also, some operating systems don''t allow zero terminated strings on principle. (There are those who believe that such constructs are unsuitable for anything beyond low-level programming.) Symbian versions 5.1 and up, for instance, are Unicode through and through; char datatypes aren''t used. It doesn''t allow zero-terminated strings as these are prone to buffer overflow issues as well as the memory management requirements mentioned by other posters.

Sure, you may THINK you can cope with all that malloc/free stuff for each and every string you deal with, but why bother? It''s a detail best left to the computer, since tedious make-work like that is what computers are *for*. Why make life harder for yourself?

For those who think std::string is ''too slow'', check your algorithm, not your tools. The standard string class is a lightweight wrapper, nothing more.

char * is fine if you''re doing simple low-level coding in C, because that''s what it was designed for. C was designed as a ''portable assembler'' at a time when few computers even supported graphics or VDUs. It certainly wasn''t intended to be used in complex applications 30 years later.


--
Sean Timarco Baggaley

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
why babble about this when it''s so clear.

If you''re going to make modifications to the string later in the code, use a string class.

If you''re not going to make modifications to the string then use char*.

Share this post


Link to post
Share on other sites