mercredi 29 mars 2017

CRT detected that the application wrote to memory after end of heap buffer (new/delete) classes

I am receiving the "Debug error" CRT detected that the application wrote to memory after end of heap. But I don't understand why and can't find any similar examples.

The full code is... Although I think it may just be a problem with main.

#include <iostream>
#include <cmath>
#include <array>

using namespace std;
// Declare global consts
const double pi = 3.1415926583;


// Base class Shape
class Shape{
protected:
    double *sides;
public:
    Shape(const int n){ //parameterized for n dimensional shape
    sides = new double[n];
}
// need virtual destructor
virtual ~Shape(){
    delete[] sides;
}
virtual double area() const = 0; // pure virtual function for area
virtual double volume() const = 0; // pure virtual function for volume
};

//////////////////////////////////////////////////////////
//Derived classes for 2D and 3D Shapes
class Shape2D : public Shape{ // inherit shape
protected:
    int n = 2; //n denotes the number of dimensions
public:
    // default constructor
    Shape2D() :Shape(n){}
    // param constructor
    Shape2D(const double side1, const double side2) :Shape(n){
        sides[0] = side1; sides[1] = side2;
    }
    virtual ~Shape2D(){} //virtual destructor
    double volume() const { cout << "trying to calculate volume of 2d   shape..." << endl; return 0; };
};

/////////////////////////////////////////////////////////////////////
//2D shapes
class Rectangle : public Shape2D{
public:
    // constructors
    Rectangle() :Shape2D() {}
    Rectangle(const double side1, const double side2) :Shape2D(side1, side2){}
    ~Rectangle(){}
    double area() const { return (sides[0] * sides[1]); }
};

int main(){
    Shape **ShapePointer = new Shape*[2];
    ShapePointer[0] = new Rectangle(2, 5);
    ShapePointer[1] = new Rectangle(1, 3);
    // clean up 
    delete ShapePointer[0];
    delete ShapePointer[1];
    delete[] ShapePointer;
    system("pause");
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire