core dumped in c++ | Sololearn: Learn to code for FREE!


core dumped in c++

Hello. Im trying to create an object wich it is from class Person and if i create only one object with persons[0].setName("John"); , i dont have any error, but if i insert another person object with persons[1].setName("Tanjil"); i have like "timeout core dumped error". I would like to know why this happens and how to fix it? Appreciate any response. Thats the program

9/1/2020 10:56:51 AM

Tanjil Khan

2 Answers

New Answer


No memory is allocated for "name" member of the class. You are trying to copy a string (c string) over uninutialized pointer. But you don"t need to do that. Since you are using string literals, you can store a pointer to it safely your setName method needs to be void setName(const char* name){ this->name = name; } And in your class you need to make the following change. declare your name member as const char* name = nullptr; change getName to return const char* instead of char* But if you still want to use strcpy in setName then you should do this void setName(const char* name) { this->name = new char[strlen(name)+1]; strcpy(this->name, name); } And you should free the memory in the destructor ~Person(){ delete[] name; }


The problem lies in `setName` function. You have not yet allocated memory for member <name> and you try to copy <name> argument over to member <name>. Personally I'd prefer std::string instead to avoid this kind of problem