简体   繁体   中英

C++: Deallocating dynamic memory when derived class object is destructed

I seem to have an issue with dynamic memory allocation.

Below you'll see a derived class that contains a pointer for a name variable that will be dynamically allocated using the void name(const char* name) method. The function is run by the Product constructor, which sets a name for the product class when the object is created. Here's the class:

namespace sict {
  class Product :public Streamable {

    char* name_;

public:

    Product(const char* name);
    virtual ~Product();

    void name(const char* name);

}

And here's the name function itself, along with the one argument constructor:

void sict::Product::name(const char * name) {
    int g = strlen(name);
    name_ = new char[g];
    strncpy(name_, name, g);
    name_[g] = 0;
}

Product::~Product() {
    delete [] name_;
    name_ = nullptr;
}

To me this code seems capable enough of created the object then destroying it peacefully whenever it exits the scope of the function it's running in. However, when the function ends and the destructor runs, the program freezes/crashes at delete [] name_ . Running the program on Visual Studio's compiler seems to yield no particular errors (other than the program freezing), but the gcc compiler detects some sort of heap corruption. Would anybody know why this is happening?

I'm not sure why Sean Cline didn't post his comment as an answer, but Sean is correct.

name_ is given g elements and then name_[g] is set to zero, but name_[g] is one past the end of the array. Either use name_ = new char[g+1]; or name_[g-1] = 0; so that you don't go past the end of the array.

Also, as several comments point out, any time you have a class that allocates memory dynamically, make sure you define the copy constructor , the assignment operator , and the destructor . If you miss one, the default implementation will perform a shallow copy , which can cause headaches for you.

A shallow copy is when the pointer is copied instead of the data it points to. In your case, if an object of this class is ever copied or assigned, you end up with two objects pointing to the same data on the heap, and they would both try to delete it when they run their destructors.

For more information on those functions, see the Rule of Three

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM