このコードを実行すると、次の画像に示すようなエラーが発生します。
GCCコンパイラで実行してみましたが、正常に動作しました。しかし、Windows上のVisual Studioで実行すると、このエラーが発生しました。
デバッグエラー!
プログラム:C:\ Users \ yudab \ source \ repos \ Project2 \ Debug \ Project2.exe
検出されたヒープ破損:0x014FD2E0の通常ブロック(#153)の後。
CRTは、ヒープバッファの終了後にアプリケーションがメモリに書き込んだことを検出しました。
いくつかのテストの後、エラーは2番目の単語を削除しようとした後にのみ表示されるようです。
#include <cstring>
#include <string>
#pragma warning(disable : 4996)
#include <iostream>
using namespace std;
void delStr(char**& lexicon, int& lexSize, char word[]);
void printAll(char** lexicon, int lexSize);
void retract2dArr(char**& arr, int& size);
int main() {
char** lexicon = new char* [3];
lexicon[0] = new char[6]{ "hello" };
lexicon[1] = new char[5]{ "test" };
lexicon[2] = new char[6]{ "world" };
int size = 3;
char removeTest[5] = { "test" }; //The first word I want to remove from the list
char removeWorld[6] = { "world" }; //The second word I want to remove from the list
printAll(lexicon, size); //First prints the entire list
delStr(lexicon, size, removeTest); //Removes the first word
delStr(lexicon, size, removeWorld); //Removes the second word
printAll(lexicon, size); //Prints the list after deleting the words
return 0;
}
void delStr(char**& lexicon, int& lexSize, char word[]) {
bool toDelete = false;
for (int i = 0; i < lexSize; i++) {
if (strcmp(lexicon[i], word) == 0) {
toDelete = true;
for (; i < lexSize - 1; i++) {
strcpy(lexicon[i], lexicon[i + 1]);
}
}
}
if (toDelete == true) {
delete[] lexicon[lexSize - 1];
retract2dArr(lexicon, lexSize);
}
return;
}
void printAll(char** lexicon, int lexSize) {
for (int i = 0; i < lexSize; i++) {
cout << lexicon[i];
if (i != lexSize - 1) {
cout << " ";
}
}
cout << endl;
return;
}
void retract2dArr(char**& arr, int& size) {
size--;
char** newArr = new char* [size];
for (int i = 0; i < size; i++) {
*(newArr + i) = *(arr + i);
}
printAll(newArr, size);
delete[] arr;
arr = newArr;
return;
}
kiran Biradarが指摘したように、strcpy
ここで責任があります。レキシコン内の各単語を前の単語に割り当てられたメモリにコピーする代わりに、lexicon
配列を使用してポインタを単純に戻す方がよいでしょう。
delStr
関数に対して次のようなものを試してください。
void delStr(char**& lexicon, int& lexSize, char word[]) {
for (int i = 0; i < lexSize; i++) {
if (strcmp(lexicon[i], word) == 0) {
delete[] lexicon[i];
for (; i < lexSize - 1; i++) {
lexicon[i] = lexicon[i + 1];
}
retract2dArr(lexicon, lexSize);
}
}
}
PStoDelete
フラグを使用する必要はありませんでした。retract2dArr
最初の内で、関数を呼び出すことができますif
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加