Sign in to follow this  

How to avoid a nightmare.... (String functions)

This topic is 4713 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

How to avoid a nightmare? Watchout for things like this... This mistake cost me 4 days of debugging (Though I found other mistakes in my code, it would have been faster to correct them later on.). This code knocks off the last 3 characters in a C-style string, or does it...
chrString[strlen(chrString)] = 0;
chrString[strlen(chrString)-1] = 0;
chrString[strlen(chrString)-2] = 0;


Share this post


Link to post
Share on other sites
Although strlen is a fast function, why call it three times when you only have to call it once?

int len = strlen(chrString);
chrString[len] = 0;
chrString[len-1] = 0;
chrString[len-2] = 0;

and moreover, if the point is to cut the last 3 characters, why not jump straight to the cut off point:

chrString[strlen(chrString)-2] = 0;

Share this post


Link to post
Share on other sites
Quote:
Original post by ProcedureX
This code knocks off the last 3 characters in a C-style string, or does it...

[ Solution omitted. ]

No, it doesn't. It knocks off the last 3 characters in any string of at least 3 characters. In a string of 2 or fewer characters, you're probably going to be doing an illegal write and getting a runtime exception somewhere.

Use std::string. It just wants to be loved! :)

Share this post


Link to post
Share on other sites
For once I'd like a thread where I wasn't recommended to use C++... [bawling]

Anyways, there are a few assumptions I didn't include in the code sample. One of them, which I see brought some critism, was the assumption that the string is larger than 3 characters.

[google] "A forum for procedural programmers" [google]

Cya all.

Share this post


Link to post
Share on other sites
Heh, that's an amusing bug.

Though I'm not exactly certain how std::string would prevent that sort of bug [the bug that exists for strings greater than 3 chars that is...]

Personally, if you're overwriting a block of data like that, using pointers and bzero/memset is more... C-style. Plus it gets you as the programmer thinking in blocks of memory rather than in words and letters, preventing such oopsies.

Share this post


Link to post
Share on other sites

This topic is 4713 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this