我在程序結束時刪除對象時出現問題。這是一個C++課程,所以我們不允許使用字符串類(還)。我有一個武器類爲武器生成一個名字,這個名字被char* result = new char[len]
實例化,然後返回給構造函數。在析構函數中,我使用delete[] this->name
刪除名稱對象。嘗試刪除對象時檢測到堆損壞(C++)
問題:
當我運行我的程序,一切都正常運行,直到程序涉及到程序的刪除部分。然後我得到這個錯誤信息:
調試錯誤!
計劃:...路徑編程...
堆損壞。結果:在正常0x0100B918塊(#198)之後。 CRT 檢測到應用程序在緩衝區結束堆 後寫入內存。
(按重試來調試應用程序)
我曾嘗試更換用delete [],反之亦然刪除,並沒有什麼區別。
任何人都可以發現我想錯的地方嗎?
main.cpp中:
int _tmain(int argc, _TCHAR* argv[]) {
// ... code ...
Weapon* weapon = new Weapon();
// ... code ...
delete weapon;
}
Weapon.cpp:
Weapon::Weapon() {
this->name = this->generateName();
// more properties...
}
Weapon::~Weapon() {
delete[] this->name;
this->name = nullptr;
}
char* Weapon::generateName() {
int pr, tp, su; // random variables for picking prefix, type and suffix
const char *prefix[10] = { // ... a bunch of names ... };
const char *type[10] = { // ... a bunch of names ... };
const char *suffix[10] = { // ... a bunch of names ... };
pr = rand() % 9;
tp = rand() % 9;
su = rand() % 9;
int len = strlen(prefix[pr]) + strlen(type[tp]) + strlen(suffix[su]) + 1;
char *result = new char[len]();
strcpy(result, prefix[pr]);
strcat(result, " ");
strcat(result, type[tp]);
strcat(result, " ");
strcat(result, suffix[su]);
return result;
}
你很可能會溢出結果 - 寫入超過分配。 –
「這是爲了C++課程,所以我們不允許使用字符串類(還)。」嘆。 CS的迷人之處在繼續。不要學習最有用的語言功能,永遠不要提及使用調試器和調試技術 – pm100