Archived

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

noxa

Creating strings for a certian length, but it messes up...

Recommended Posts

Hello all, I''m trying to do a little class to make strings easier to work with (CString is nice, but it''s all I use in MFC so I want to trash it). I have my class working, all the bells and whistles of CString and more (conversion to and from all the standard data types!) but I''m having a problem. In a few of my functions (and only at certian times) when I try to allocate the memory for the strings, 3 characters (''ý''s) are added to the end for no reason. Here''s some code: (m_pcData is a char* with the string in it, LPSTR = char*) CStr CStr::Left(int iLength) { LPSTR str = new char[iLength]; for( int i = 0; i <= iLength; i++ ) str = m_pcData[i]; return( CStr(str) ); } Now, this function looks simple (and it is), yet it''s been baffeling me for a week! Say m_pcData is "hello" and iLength is 2, the return value is "heýýý", not "he" like it should be! I have a Mid and Right function similar to this that do the same thing. The weird part is that only on some calls does this behavior manifest... Does anyone know what is causing this? In debug mode I can see that right as the string is created, it has the 3 ''ý''s on it (in addition on the NULL char''s allocated for the string), and they stay there the whole time! bahhhhhh ~noxa~ Ben Vanik

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
If you''re using C++, why not use the string class from the STL? Just include (or and use namespaces).

Erik

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Hmm, something''s missing from that post.
You should include string and use namespace std.

Erik

Share this post


Link to post
Share on other sites
As to why this is happening - it''s down to malloc, and the way it works. malloc (which is behind the new call) allocates either no memory (failure) or /at least/ as much memory as is required (success).

So, if you malloc 10 bytes, you might get 10, or you might get 12, or you might get something else. This happens so that boundary alignment is maintained, increasing general performance (at the expense of a few bytes of memory).

This is why the terminating NULL is required.

TheTwistedOne
http://www.angrycake.com

Share this post


Link to post
Share on other sites
The terminating \0 is required cos otherwise none of the standard C functions know where the end of the string is! That would be the same whether malloc always allocated the exact amount you asked for or not. Technically you could output your entire process memory with that last CStr() call, if there were no zeros in that area of memory.

Share this post


Link to post
Share on other sites