简体   繁体   中英

Unable to delete member pointer to array in destructor for class

So I am trying to delete my member pointer m_memory as it points to an array of char . When I try to delete the array that m_memory points to using delete[] I end up triggering breakpoints. I tried initializing m_memory as a nullptr before using new but it still triggered the breakpoint. Just wondering what my error is.

Header File:

#ifndef FISH_H
#define FISH_H
#include <iostream>
class Fish {
public:
    Fish(int capacity, std::string name);// Constructor
    Fish(const Fish &other); // Copy Constructor
    ~Fish(); // Destructor
    Fish &operator=(const Fish &other); // Assignment Operator
    void remember(char c); // Remember c
    void forget(); // Clears memory by filling in '.'
    void printMemory() const;// Prints memory
    std::string getName();
protected:
    const char* getMemory() const;// Returns memory
    int getAmount() const; // Returns amount remembered
    int getCapacity() const; // Returns memory capacity
private:
    std::string m_name;
    char * m_memory;
    int m_capacity;
    int m_remembered;
int m_replace;

};
#endif

Implementation file:

#include “fish.”

Fish::Fish(int capacity, std::string name) {// Constructor
    this->m_capacity = capacity;
    if (capacity > 0) {
        this->m_capacity = capacity;
    }
    else {
        this->m_capacity = 3;
    }

this->m_name = name;
this->m_memory = new char[this->m_capacity];
this->m_memory[this->m_capacity] = '\0';

for (int i = 0; i < this->m_capacity; i++) {
    this->m_memory[i] = '.';
    }
    this->m_remembered = 0;
    this->m_replace = 0;
}


Fish::~Fish() // Destructor
    {
        delete [] this->m_memory; //exception thrown, breakpoint triggered
    }

Main:

#include "fish.h"
int main() {
    Fish *nemo = new Fish(3, "nemo");
    nemo->~Fish();

}
this->m_memory = new char[this->m_capacity];
this->m_memory[this->m_capacity] = '\0';

This writes outside the array. this->m_capacity is 3, so you're allocating 3 chars and then writing to the 4th one.

The computer isn't required to detect this problem. Microsoft is trying to be helpful here by detecting it, but their detection only happens when you free the memory. If you run your program in the debugger, you should see some messages in the Debug Output window explaining why your program crashed.

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