What int the heck is wrong with my string class?

Started by
4 comments, last by Mike 24 years, 5 months ago
I haven't downloaded your source, but I think I know what your problem is.

Change this:

m_chrString = new char[ length ];

to this:

m_chrString = new char[ length + 1 ];

Remember, you must allocate one more than the length to accomodate the null terminator at the end of the character array.

Hope this helps!

Josh

Advertisement
Excuse me for a moment while I go beat my head into a wall. Thanks, you were right.
Of course the alloc with length+1 was right, but here's my problem with that answer. What does that have to do with the delete call? delete [], does NOT in any way care anything about the contents of your string, nor the NULL terminator, it just looks before the address of the array and checks how much was allocated, then it deletes that much. I don't see how fixing your alloc error would fix your delete problem. Perhaps I'm ignoring the fact that maybe your program allocated two strings in a row and therefore the alloc error cause the first string to store it's NULL terminator over the control information stored in front of the second string (which in turn would crash delete). Oh well....guess I'll never know for sure.
Xai: You're probably right. Whenever you write past the allocated space you get, in Microsoft terminology, "undefined" results. As in you could be fine, the program could crash.

Or the whole computer could ignite in flames (only with the Microsoft(tm) Self-Destruct kit, sold seperately)

- Splat

Rather than post the whole class here, I've uploaded the code (and VC++ 6.0 project and workspace) to mike010.hypermart.net/source.zip .

For some reason the class cuases the simple program I included with the source (I mean real simple program. It has no more than a main.). The problem occures whenever I try to do the following:

code:
delete [] m_chrString;

Yes, m_chrString is an array of type char that was create using:

code:
m_chrString = new char[ length ];

This is basic stuff, and it has me rether agrivated that I cannot find the fault im my code. Please do not respond with a cratique of my class, just tell me why its crashing the program.

Apropos garbage collection !!
<b>/NJ</b>

This topic is closed to new replies.

Advertisement