Problem occurs in the destructor. Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

Asked 2 years ago, Updated 2 years ago, 95 views

I keep getting errors from the extinction person, but I'm using xcode, so I don't know which part is the problem ㅜ<

#include <stdio.h>
#include <iostream>
#include <cstring>

using namespace std;

class Person{
    char* name;
    char* addr;
public:
    Person(const char *name, const char *addr){
        this->name= new char[strlen(name)+1];
        strcpy(this->name,name);
        this->addr= new char[strlen(addr)+1];
        strcpy(this->addr,addr);
        cout<<"Create Person Object" ("<<name<<")"<<endl;
    }
    ~Person(){
        cout<<"Remove Person Object" ("<<name<<")"<<endl;
        delete [] name;
        delete [] addr;
    }
    void print() const{
        "It's ""<<<name<<endl;" living in ""cout<<addr<<<<endl;""
    }

    //Create Move Creator
    Person(Person&& human2) : name{human2.name}, addr{human2.addr} {
        human2.name=nullptr;
        human2.addr=nullptr;
        cout<<"Person has moved~"<<endl;
    }
    void print(){
        if((this->name == nullptr)&&(this->addr == nullptr)){
            cout<<"This data is already missing"<<endl;
        }
        else{
            cout<<"Name:"<<name<<"Address:"<<addr<<<endl;"
    }
};

int main()
{

        cout<<"Move C to D to execute constructor"<<endl;
        Person C ("Kim Jjon-tteok" ("Seoul Metropolitan Government");
        Person D = move(C);
        C.print();
        D.print();
        cout<<endl;
} 

<Result value>

Created a Person object (Kangshiru)

Move C to D Run the constructor

Person Create Object (Kim Chewy Rice Cake)

Person, I'm done moving

This data is already missing

Name: Kim Jjon Tteok Address: Seoul Metropolitan Government

Person Remove Object (Kim Chewy Rice Cake)

Person Remove object ((lldb) //where Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) error occurs.

I think there's a problem with nullptr. What is it?

c++ destructor

2022-09-20 19:31

1 Answers

The reason for the error is that when the destructor is called, the name is output as cout even if the name is NULL.

You can delete it and change it to print it out only when it is not NULL as shown below.

    ~Person() {
        if (name)
        {
            delete[] name;
            cout << "Remove Person Object" ("<< name <<")" << endl;
        }
        if(addr)
            delete[] addr;
    }


2022-09-20 19:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.