向量运算中的双重释放或损坏输出错误C ++

问题描述

当我运行以下代码时,它给出了 double free or corruption (out) Aborted (core dumped)错误。我尝试调试,但是我仍然不明白为什么此代码不起作用的原因。我尝试搜索类似的错误,但大多数错误都涉及原始指针和错误的内存分配,而事实并非如此。

#include <vector>
#include <algorithm>
#include <cmath>

float median(std::vector<float> array){
    std::sort(array.begin(),array.end());
    std::size_t length = array.size();
    if (length % 2 != 0){
        return array[(length - 1)/2];
    }
    float median = (array[length/2 - 1] + array[length/2]) / 2.0;
    return median;
}

int main(int argc,char const *argv[])
{
    const int DIM = 32;
    const int AUX_COLS = 4;
    std::vector<float> weights(DIM * AUX_COLS);
    for (std::size_t j = 0; j < AUX_COLS; j++) {
        std::vector<float> column(DIM);
        for (std::size_t i = 0; i < DIM; i++) {
            column[i] = i * i + j * j;
        }
        float colMedian = median(column);
        for (std::size_t i = 0; i < DIM; i++) {
            weights[i * DIM + j] = std::abs(1.0f);
        }
    }
    return 0;
}

解决方法

weights[i * DIM + j] = std::abs(1.0f); 这是错误的,因为

DIM*(DIM-1)+(AUX_COLS-1) > DIM * AUX_COLS == weights.size()

您可以通过注释掉程序的某些部分来找到此错误。如果它没有错误地运行,则表明该错误在您注释掉的部分中(或者在由于注释而无法运行的代码中)。