![](/img/trans.png)
[英]_BLOCK_TYPE_IS_VALID(pHead->nBlockUse) crash in C++
[英]resize dynamically allocated memory C++ with ASSERT“ _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) ”
您好,我正在寫一些代碼來調整動態分配內存的大小。 這是我的代碼初始化的一部分:
int size = 1;
string *rev = new string[size];
調整大小:
if (j >= size / 2){
size = size * 2;
string *temp = rev;
rev = new string[size];
memcpy(rev, temp, (size / 2)*sizeof(string));
delete[] temp; // <- here causes the error!
}
當我注釋掉“ delete [] temp”時,我的代碼工作正常,但內存泄漏。 因此,我該如何處理此錯誤消息“斷言”。 請幫忙! 謝謝!
因為有人指出斷言是由我的代碼的其他部分引起的。 這是完整版本,只需按給定句子中的相反順序打印單詞即可。
void ReverseWords(string &sentence) {
char *str = new char[sentence.size()+1];
int size = 1;
string *rev = new string[size];
int j = 0;
int n = 0;
int m = 0;
for (unsigned int i = 0; i < sentence.size(); i++){
str[n] = sentence.at(i);
n++;
if (str[n-1] == ' '){
str[n-1] = '\0';
if (j >= size / 2){
size = size * 2;
string *temp = rev;
rev = new string[size];
memcpy(rev, temp, (size / 2)*sizeof(string));
delete[] temp;
}
rev[j] = str;
cout << rev[j] << endl;
cout << j << endl;
j++;
memset(str, 0, sentence.size() + 1);
n = 0;
}
}
str[n] = '\0';
rev[j] = str;
int rev_size;
for( rev_size = 0; !rev[rev_size].empty(); rev_size++){
}
rev_size--;
while (rev_size >= 0){
if (rev_size == 0){
cout << rev[rev_size] << endl;
break;
}
cout << rev[rev_size] << " ";
rev_size--;
}
delete[] rev;
delete[] str;
return;
}
編輯:我修復了此錯誤,感謝@πάνταῥεῖ和@Retired Ninja。 導致斷言的錯誤是我將memcpy函數濫用為非pod類型。 我已將memcpy更改為:
for (int m = 0; m < j; m++){
rev[m].assign(temp[m]);
}
現在一切正常! 多謝你們。
失敗的原因是您正在使用memcpy
復制std::string
。 std::string
不是Pod類型,不能安全地按位復制,必須使用賦值運算符或復制構造函數的方式復制它。
更好的解決方案是使用標准容器,例如std::vector<std::string>
或std::deque<std::string>
來處理大小調整和正確復制。
您還可以使用std::stringstream
拆分單詞並將它們存儲在容器中,從而大大簡化算法,但是我認為這是為了賦值,並且不想完全重寫您的函數,因此我將向您展示解決問題所需的最低限度。
代替:
memcpy(rev, temp, (size / 2)*sizeof(std::string));
用這個:
for(int i = 0; i < size / 2; ++i)
{
rev[i] = temp[i];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.