Search code examples
c++vectorallocation

double free or corruption (out) error in operations with vectors (c++)


When I run the following code it gives double free or corruption (out) Aborted (core dumped) error. I tried debugging, but I still don't understand the reason why this code doesn't work. I tried searching for similar errors, but most of them deals with raw pointers and bad memory allocation, which doesn't seems to be the case.

#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;
}

Solution

  • weights[i * DIM + j] = std::abs(1.0f); that is wrong, since

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

    You can find this errors by commenting out parts of your program. When it is running without error, it is a hint that the bug is somewhere in the part that you comment out (or in the code that is not run because of your comment).