Deleting dynamic arrays?

会有一股神秘感。 提交于 2019-12-24 18:09:06

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/20101172/deleting-dynamic-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!