Skip to main content
gamedev.net
🔒 Locked

Strange delete error

Started by Zidane Jul 2, 2004 at 7:53 AM 4 replies 550+ views
Original Post
Zidane
Zidane
Hey, I have this code in my file library:


char* temp = new char[4];

	memset(temp, 0, 5);
	f.read((char*)temp, 4);
	header.type = std::string(temp);

	memset(temp, 0, 5);

	f.read(temp, 4);
	header.version = std::string(temp);

	delete[] temp;

Now when the code reaches the delete[] temp line i get this debug error: "Damage after Normal Block {#59}" Anyone got any ideas what it means?, if I comment the delete line out it works fine. The only thing I think it could be is that std::string is still using the pointer, but does it copy the string when it is created? But it cant be that, due to the fact that the header.type string would be set to the second string read, but it isnt. Strange...
DigitalDelusion
DigitalDelusion
You're memsetting past the array bounds and hence trashing your heap.

What you should be doing is either increase the array size by one, or use a static array (still need that extra char for termination) or use the std::string constructor that also takes length.

Anyhow you should stop writing outside the bounds of your array.
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
tomek_zielinski
tomek_zielinski

Zidane is right:


char* temp = new char[4]; // temp four-element array
memset(temp, 0, 5); // you set FIVE elements

you propbalby thought that NULL string terminator is automatically allocated, but it's like that only when doing sth like this;

char *temp = "dsfdsafas"
or
char temp[] = "fdfdsafdaf";

You should do 'new char[5]'
www.tmreality.com
DigitalDelusion
DigitalDelusion
Quote:
Original post by tomek_zielinski
Zidane is right:
...


Actually I'm right. And your post clearly shows that.
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
DigitalDelusion
DigitalDelusion
I'm bored so I can as well post some code:

this should work:
char* temp = new char[5];memset(temp, 0, 5);f.read(temp, 4);header.type = std::string(temp);f.read(temp, 4);header.version = std::string(temp);delete[] temp;


as should this:
char temp[5] = {0};f.read(temp, 4);header.type = std::string(temp);f.read(temp, 4);header.version = std::string(temp);delete[] temp;


and this:
char temp[4];f.read(temp, 4);header.type = std::string(temp, 4);f.read(temp, 4);header.version = std::string(temp, 4);


and assuming the header stores std::strings here's one with
some pointless micro optimization.
char temp[4];f.read(temp, 4);header.type.swap( std::string(temp, 4));f.read(temp, 4);header.version.swap( std::string(temp, 4));
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.