Deleting dynamic array of char in C++
I have this class, with the atribute 'word'
class Node {
char *word;
Inside the Node constructor, I do this asignation:
word = new char[strlen(someword)];
In the destructor of the Node class, I try to delete the contents pointed by word:
delete []word;
I obtain the next message after executing the programs:
"Heap block at 003E4F48 modified at 003E4F51 past requested size of 1"
Wha开发者_如何学Pythont am I not doing well?
You have a buffer overflow in your program, somewhere else in code you didn't post. The problem is that you're not allocating enough memory -- you don't leave room for the null terminator at the end of your string. You should change the allocation to this:
word = new char[strlen(someword) + 1]; // +1 for null terminator
...
strcpy(word, someword);
You should be thankful your C runtime caught your error. In most cases, a one byte buffer overflow will result in silent memory corruption and not be detected until much later, if ever.
You should also consider using the std::string
class, which automatically manages the memory for you, so you don't have to deal with subtle issues like this.
strlen
will return the length of the string but will not account for the null-terminating extra byte. My guess is that you are then copying in a string and appending a null-byte but you did not account for it when you originally allocated the memory. Try changing the code to read:
word = new char[strlen(someword) + 1];
You have a corrupt heap - somewhere else in your code you are writing outside the allocated memory or deleting something you shouldn't be - are you sure you don't mean strlen(someworrd) + 1?. The best solution to this problem is to use a std:;string or a std::vector rather than a dynamic array.
精彩评论