Jim
Jim

Reputation: 171

C++ crash occur when calling delete on a pointer

I have written a small program using struct and pointers(->). So I have declared an object pointer which point to another object from the same struct. But when ever delete is invoked on the application would just crash.

Here is the error

Debug Assertion Failed
File:f:\dd\vctools\crt_bld\self_86x\crt\src\dbgdel.cpp
Line 52
Expression:_BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)

And here is my code also (p.s This error does not occur when I removed delete from my program)

#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;
}

and based on my own knowledge (please correct me if I am wrong)

Son* info = new Son;

This pointer (info) has a new syntax and should be deleted like this

delete info;

And not really sure why did I get this error

Upvotes: 0

Views: 854

Answers (1)

juanchopanza
juanchopanza

Reputation: 227370

When you do this

info = &Person;

you make info point to an object that is not dynamically allocated. So you can't call delete on it. Besides that, you leak the newed Son object it originally pointed to. In any case, there seems to be no reason to use dynamic allocation in your code example.

Upvotes: 7

Related Questions