편집 기록

편집 기록
  • 프로필 알 수 없는 사용자님의 편집
    날짜2017.10.10

    C++ 메모리해제 Debug Assertion


    #include <iostream>
    #include <fstream>
    //http://is03.tistory.com/3 HOW to use eof
    
    using namespace std;
    #define FILENAME "data.txt"
    ifstream fin;
    
    class Matrix {
    
    private:
        int size;
        int numOfNonZero;
        int* row;
        int* col;
        int* value;
    
    public:
        Matrix(); // constructor
        Matrix(const Matrix&); // copy constructor
        ~Matrix();
        void display();
        void getData();
        Matrix operator*(const Matrix&);
    };
    Matrix::Matrix() {
    
    }
    void Matrix::getData() {
    
        fin >> this->size;
        fin >> this->numOfNonZero;
        row = new int[numOfNonZero];
        col = new int[numOfNonZero];
        value = new int[numOfNonZero];
    
        for (int i = 0; i < numOfNonZero; i++) {
            fin >> row[i] >> col[i] >> value[i];
        }
    }
    Matrix Matrix::operator*(const Matrix& rhs) {
        Matrix ans;
        return ans;
    }
    void Matrix::display() {
        cout << "The Matrix is : " << endl;
        for (int i = 0; i < this->numOfNonZero; i++) {
            cout << row[i] << " " << col[i] << " " << value[i] << endl;
        }
    
    }
    
    Matrix::~Matrix() {
        if (this->row != NULL) {
            delete[] this->row;
            delete[] this->col;
            delete[] this->value;
        }
    }
    
    Matrix::Matrix(const Matrix& rhs) {
        this->size = rhs.size;
        this->numOfNonZero = rhs.numOfNonZero;
    
        this->row = new int(numOfNonZero);
        this->col = new int(numOfNonZero);
        this->value = new int(numOfNonZero);
    
        for (int i = 0; i < numOfNonZero; i++) {
            this->row[i] = rhs.row[i];
            this->col[i] = rhs.col[i];
            this->value[i] = rhs.value[i];
        }
    
    }
    
    int main() {
        fin.open(FILENAME);
    
        Matrix A, B, C;
        A.getData();
        B.getData();
        A.display(); B.display();
    
        C = A * B;
    
        return 0;
    }
    
    

    Visual Studio에서 실행하면 Debug Assertion이 발생하더라구요.. 자세한 오류명은 _CrtIsValidHeapPointer(block)입니다. 디버깅 하면서 어디서 오류가 발생하는지 보니, 소멸자의 delete에서 발생하더라구요. 왜 이런 오류가 발생하는 지 잘 모르겠습니다.

    1. 왜 이런 오류가 발생하나요?
    2. 그리고 _CrtIsValidHeapPointer(block) 이 오류가 어떤 오류를 나타내는지 궁금합니다.

    ps. 메인에서,
    Matrix C; C = A * B; 가 아니라, Matrix C = A * B;

    이렇게 하면 또 오류가 발생안하는 군요..;;

    설명점 해주시면 감사하겠습니다..!!!