向量运算中的双重释放或损坏(out)错误(C++)

double free or corruption (out) error in operations with vectors (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()

您可以通过注释掉部分程序来发现此错误。当 运行ning 没有错误时,这表明该错误位于您注释掉的部分(或由于您的注释而未 运行 的代码中)。