Efe Gürkan
Efe Gürkan

Reputation: 23

Deleting dynamic arrays?

I'm having problems about deleting dynamic arrays in my project.

First appear:

void StudentReviewSystem::addCourse( const int courseId, const string courseName )
{
    int i = findCourse( courseId );

    if ( i == -1 )
    {
        int newNum = numberOfCourses + 1;
        Course *newCourses = new Course[newNum];
        for ( int j = 0; j < numberOfCourses; j++ )
        {
            newCourses[j] = courses[j];
        }
        Course aCourse(courseId, courseName);
        newCourses[numberOfCourses] = aCourse;
        //delete[] courses;
        courses = newCourses;
        numberOfCourses = newNum;
        cout<< "Course "<< courseId <<" has been added."<< endl;
    }
    else
    {
        cout<< "Course "<< courseId <<" has already exist."<< endl;
    }
}

courses is a pointer which was defined in my header. If I comment out the delete line, code works just fine, otherwise, program crashes.

Another appear:

StudentReviewSystem::StudentReviewSystem()
{
    numberOfCourses = 0;
    courses = new Course[0];
}

StudentReviewSystem::~StudentReviewSystem()
{
    //delete[] courses;
}

I know I must delete my dynamic arrays to avoid memory leaks, but whenever my destructor is called, program crashes so I comment out that line too.

Whenever I try to delete a dynamic array, program crashes no matter what I do.


It turned out that you can't delete[] an array with size 0. So, I check for size every time I want to delete an array. But does a 0 size array causes memory leak?

Upvotes: 1

Views: 1008

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310970

Either you assign one object of type StudentReviewSystem to another object of the same type without explicitly defining the copy assignment operator (or a copy constructor) or the compiler has a bug when a zero length array is allocated.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254461

If your class manages resources, then you usually need a destructor, copy-constructor, and copy-assignment operator, per the Rule of Three. My guess is that you don't have these, so the class has invalid copy semantics: copying it will just copy the pointer, not the dynamic array, leaving two objects both wanting to delete the same array.

Either implement or delete the copy functions, or (better still) don't manage the resources yourself: use std::vector<Course> to do the work for you. You won't need the destructor either if you do that, and addCourse would be much simpler.

Upvotes: 2

Related Questions