对象可能在被释放C ++后被修改了?

时间:2016-01-20 07:10:29

标签: c++ dynamic-arrays dynamic-allocation

此函数将元素插入动态数组中。当我注释掉delete []数组时,我得到了这个错误,但是如果我没有,那么一切正常......那就是我插入数组的顺利进行。安迪想出了什么?

错误:释放对象的校验和不正确 - 对象可能在被释放后被修改。 ***在malloc_error_break中设置断点以进行调试

#include <iostream>

#include "dynamic_array.h"

using namespace std;

dynamic_array::dynamic_array() {
    try {
        array = new int[0];
                size = 0;
        allocated_size = 5;
    } catch ( const std::bad_alloc& e ) {
            throw exception(MEMORY_EXCEPTION);
    }           
}

dynamic_array &dynamic_array::operator=(const dynamic_array &a) {

    return *this;
}

dynamic_array::~dynamic_array() {
    delete [] array;
}

int dynamic_array::get_size(void) const {
    return size;
}

int dynamic_array::get_allocated_size(void) const {
    return allocated_size;

}

int& dynamic_array::operator[](unsigned int i) {
    if (i >= get_size())
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
    else
        return array[i];
}

const int& dynamic_array::operator[](unsigned int i) const {
    if (i >= get_size())
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
    else
        return array[i];

}

void dynamic_array::insert(int x, int i) {

    try {if (i < 0 || i > get_size())
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
        if(size == 0){
        array[i] = x;
        size++;}
        else if(allocated_size == size){
            int *array2;
            array2 = new int[allocated_size+5];
            allocated_size += 5;
            for(int j=0;j<=size-1;j++)
            array2[j] = array[j];
            //delete [] array;
            array = array2;
            shift_right(i,size-1,1);
            array[i] = x;
            size++;
        }
        else{
            shift_right(i,size-1,1);
            array[i] = x;
            size++;
        }
    } catch ( const std::bad_alloc& e ) {
            throw exception(MEMORY_EXCEPTION);
    }
}

void dynamic_array::shift_right(int start, int end, int delta) {
    if(0 <= start && start <= end & end <= size){
    int temp [size];
    int s = 0;
    for(int i = start; i <= end; i++){
    temp[s] = array[i];
    s++;
    }
    int d = 0;
    for(int j = start + delta ; j< sizeof(temp)+end; j++){
    array[j] = temp[d];
    d++;}
}

}

1 个答案:

答案 0 :(得分:0)

shift_right出现问题,我不得不重写..转换超出了为数组分配的大小,修复时错误消失了。