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

标签 c++ pointers runtime-error

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

这也是我的代码(p.s 当我从程序中删除 delete 时不会发生此错误)

#include <iostream>
#include <string>
#include <Windows.h>
#include <sstream>
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;

这个指针(信息)有一个新的语法,应该像这样删除

delete info;

我不太确定为什么会出现此错误

最佳答案

当你这样做的时候

info = &Person;

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

关于在指针上调用 delete 时发生 C++ 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21514731/

相关文章:

c++ - QFile VS ifstream。哪个更快?

c++ - 如何在运行时设置数组大小而不构造对象?

c++ - 删除无效指针是否保证删除正确的大小?

c - 为什么 SDL2 窗口会淡出?

ruby-on-rails - Rails - 未显示实际错误 - 显示带有 header 数组的机架/etag 错误

命令提示符中的 Javac 命令不执行文件

c++ - 根据 GPU 计算能力定义 MACRO

c++ - 将对象移到 vector C++的前面

GCC 的 C++ 库问题

c++ - 在p=new string[0]和p=new int[0]之后,为什么string版本在delete[] p时会崩溃?