动态内存问题 (_CrtIsValidHeapPointer)

Issues with Dynamic Memory (_CrtIsValidHeapPointer)

我不确定为什么我的程序是 seg。每次我 运行 它使用 Visual Studio 2015 编译器时都会出错,但使用 GNU 编译器编译得很好。任何人都可以深入了解这个问题吗?

这通常包含在一个名为 EVector.h 的文件中,但我在下面添加了它以防万一需要它

#include<iostream>

class EVector
{
public:
    EVector();
    ~EVector();

    //Operator Overloading
    friend std::istream& operator>>(std::istream&, EVector&); //Input Stream
    friend std::ostream& operator<<(std::ostream&, EVector&); //Output Stream
    EVector operator=(EVector&);

private:
    double* Tuples;
    int dimension;
};

这是我的 EVector.cpp 文件

#include<iostream>

EVector::EVector() {
    dimension = 0;
    Tuples = NULL;
}

这就是我通常删除动态内存的方式,但由于某些原因在这个程序中它导致了分段错误(或者至少 Visual Studio 这么认为)

EVector::~EVector() {
    if (Tuples != NULL) {
        delete[] Tuples;
    }
}

其余 EVector.cpp

istream& operator>>(istream& instream, EVector& vector) {
    cout << "Enter the dimension of the Euclidian Vector: ";
    instream >> vector.dimension;

    vector.Tuples = new double[vector.dimension];
    cout << "Enter the Tuple's Values (The program will take values until all dimensions are full)" << endl;

    //Take in Tuples values
    for (int x = 0; x < vector.dimension; x++) {
        cout << "Enter a Value (" << (vector.dimension - x) << " value(s) left): ";
        instream >> vector.Tuples[x];
    }

    return instream;
}

我想这可能与这个函数有关,这是我第一次重载 << 和 >> 操作数

ostream& operator<<(ostream& outstream, EVector& vector) {
    outstream << "Dimension: " << vector.dimension << endl;
    outstream << "Tuple's Values: ( ";
    for (int x = 0; x < vector.dimension; x++) {
        outstream << vector.Tuples[x] << " ";
    }
    outstream << ")";

    return outstream;
}

深层复制功能(我的作业规范要求)

EVector EVector::operator=(EVector& vector) {
    if (this == &vector) {
        return *this;
    }

    if (Tuples != NULL) {
        delete[] Tuples;
    }

    dimension = vector.dimension;
    Tuples = new double[dimension];

    for (int i = 0; i < dimension; i++) {
        Tuples[i] = vector.Tuples[i];
    }

    return *this;
}

可能是双重删除。您的深拷贝会复制您的 EVector 元素。 但是那些包含一个指针。 如果为这两个调用析构函数,它将发生段错误。 要么在复制时使 Toubles 指针无效,要么进行真正的深度复制并调用额外的 new[] 来分配复制对象中的 Tubles 指针。