我很清楚,有這樣的無數問題,但我搜索了幾個小時,並不明白我做錯了什麼,所以我會非常感謝你的幫助。 (我是編程新手)刪除[]導致堆腐敗
我需要創建一個字典管理器作爲我家庭作業的一部分,但我似乎有刪除單詞的問題。 我收到一條錯誤消息「...觸發了一個斷點」。
人們遇到這個問題的通常答案是,這是由越界引起的堆腐敗,但我無法看到是否以及如何造成這種情況。
我已經做了類似的公交信息管理,它的工作完美,使我更加困惑...(顯然,我沒有使機制完全相同,但即使看了我以前的代碼我couldn 「T隔離問題)
我加入我相信是關注的功能,
加法功能:
void Add_Word(char**& dictionary, int& dictionary_size, char word[])
{
char** temp = new char*[dictionary_size + 1]; // Create a new array of appropriate size.
int i;
for (i = 0; i < dictionary_size; i++)
{
temp[i] = dictionary[i]; // Copy head pointers addresses for all existing items.
}
temp[i] = new char[strlen(word)]; // Add the space for the new word,
temp[i][strlen(word)] = '\0'; // mark its end
strcpy_s(temp[i], strlen(word) + 1, word); // then copy it.
// I'm really not so sure about what I should put in the buffer length but
// strlen(word) + 1 seemed to work... I know... not good, but strlen(word) alone caused a problem.
if (dictionary_size > 0)
delete []dictionary; // Delete previous head pointers array if there are any and
dictionary = temp; // reset the main pointer to the address of the new one.
dictionary_size++; // Finally, increase dictionary_size.
}
的刪除功能:
void Delete_Word(char**& dictionary, int& dictionary_size, char* word)
{
// !!! This is where the crash thingy happens.
delete[] Search_For_Word(dictionary, dictionary_size, word); // Delete the word from the dictionary.
// Search_For_Word returns a pointer to the word it receives, from the dictionary.
char** temp = new char*[dictionary_size - 1]; // Create a new array of appropriate size.
int i;
for (i = 0; i < dictionary_size; i++)
{
if (dictionary[i][0])
temp[i] = dictionary[i]; // Copy the head pointers of the existing
// items to the new array except for the deleted word.
}
delete[] dictionary; // Delete previous head pointers array and
dictionary = temp; // reset the main pointer to the address of the new one.
dictionary_size--; // Finally, decrease dictionary_size.
}
編輯:任何過分低效或明顯損壞的部分都可能是由於我弄亂了我的代碼,試圖自己弄清楚這一點(比如提到strlen的3次調用(再次感謝, kfsone ...),或者忘記爲'\ 0'+1來標記一個字符串的結尾 - 實際上,不,如果我們明白你不會告訴我我的錯誤@。@)。
至於我處理字符而不是字符串和載體的原因,請允許我引用自己:「...作爲我的作業的一部分」。我剛剛開始編程。那我想在掌握基本知識之前繼續使用更舒適的高級工具。
** AHRRG!**爲什麼你要處理原始'char'指針來實現這個[tag:C++]?使用s.th.比如'std :: map',請忘記獲取內存管理權限! –
這是怎麼回事:temp [i] = new char [strlen(word)];它必須是strlen(word)+1;這就是你的腐敗發生的地方 –
我意識到你將它標記爲C++,因爲你使用'new'和'delete',但是你正在做的是* C + *或* C# - *,而不是C++。我想你會搞砸堆'刪除[] Search_For_Word ...',但你的代碼看起來有多種錯誤(錯過1字符串錯誤等),你顯示對指針和C字符串的理解很差,而你不要使用C++的任何實際方面。以下兩個語句中的任何一個都會替換大部分代碼,消除錯誤並且效率更高。 'std :: vector','std :: vector >'。 –
kfsone