我用结构和指针( - >)编写了一个小程序.所以我已经声明了一个指向同一结构中另一个对象的对象指针.但是当在应用程序上调用delete时会崩溃.
这是错误
Debug Assertion Failed File:f:\dd\vctools\crt_bld\self_86x\crt\src\dbgdel.cpp Line 52 Expression:_BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)
这里也是我的代码(ps当我从程序中删除删除时不会发生此错误)
#include#include #include #include using namespace std; //declare structure to store info about Billy struct Son{ string name; string crush; int age; string hobbies[3]; }Person; int main(){ string sAge; int i; Son* info = new Son; info = &Person; //user interface //Person's name cout << "Person's name: "; getline(cin, info ->name); //inputs person's name //Person's age cout << "Person's age: "; //inputs person's age getline(cin,sAge); stringstream ss; ss << sAge; ss >> info->age; info->age = atoi(sAge.c_str()); //for loop to get hobbies for(i = 0; i < 3; i++){ cout << "Write your hobby[" << i <<"]: "; getline(cin,info ->hobbies[i]); //inputs the person hobby three times } //Person's crush cout << "Write your crush name: "; getline(cin, info ->crush); //inputs the person's crush *opitional* //output statement cout << "Name: " << info ->name << endl; //display name cout << "Age: " << info ->age << endl; //display age for(int j = 0; j < 3; j++){ //display hobbies cout << "Hobbies[" << j << "]: " << info ->hobbies[j] << endl; } cout << "Crush: " << info ->crush << endl; //display crush cout << "Deleting memory" << endl; delete info; info = NULL; system("pause"); return 0; }
并根据我自己的知识(如果我错了请纠正我)
Son* info = new Son;
此指针(info)具有新语法,应该像这样删除
delete info;
并不确定为什么我会收到此错误
当你这样做
info = &Person;
你info
指向一个没有动态分配的对象.所以你不能在上面调用删除.除此之外,您泄漏了Son
它最初指向的新对象.无论如何,似乎没有理由在代码示例中使用动态分配.