在指针上调用delete时发生C++崩溃

 NethJ 发布于 2023-01-29 18:52

我用结构和指针( - >)编写了一个小程序.所以我已经声明了一个指向同一结构中另一个对象的对象指针.但是当在应用程序上调用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;

并不确定为什么我会收到此错误

1 个回答
  • 当你这样做

    info = &Person;
    

    info指向一个没有动态分配的对象.所以你不能在上面调用删除.除此之外,您泄漏了Son它最初指向的新对象.无论如何,似乎没有理由在代码示例中使用动态分配.

    2023-01-29 18:56 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有