Warm tip: This article is reproduced from stackoverflow.com, please click
c++ class malloc this

C++ Object Segmentation Fault (core dumped) Error

发布于 2020-03-27 15:45:11

I am new to C++, so please, take it easy on me, so I have the following class:

class DATA
{
    private:
        char* Name;
        char* Address;
        int Id;
        void initData(int size=200)
        {
            (this->Name)=(char*)malloc(sizeof(char)*size);
            (this->Address)=(char*)malloc(sizeof(char)*size);
        }
    public:
        void readData(void)
        {
            this->initData();
            printf("Enter Name: "); scanf("%s\n",this->Name);
            printf("Enter Address: "); scanf("%s\n",this->Address);
            printf("Enter Id: "); scanf("%d\n",&(this->Name));
        }
        void printData(void)
        {
            printf("Name: %s",this->Name);
            printf("Address: %s",this->Address);
            printf("Id: %d",this->Id);
        }
};

But when I initialise an object and then call the public methods, the following happens:

Enter Name: John Doe
Enter Address: 53 Olive, St.
Segmentation fault (core dumped)

So, if anyone can tell me why (I know what is segmentation fault, but don't get it why is it here).

Questioner
AGawish
Viewed
19
Wander3r 2020-01-31 17:03

In the method readData

     printf("Enter Id: "); scanf("%d\n",&(this->Name));

You are supposed to take read Id which is an integer, but reading into string this->Name instead. Either

scanf("%d\n",&(this->Id));

As you are using C++, it's convenient and easier to use cin and cout than C-style scanf and printf and running into these kind of issues.

cin >> Id;