A C++ core dump error occurs.

Asked 2 years ago, Updated 2 years ago, 64 views

When you know the minimum and maximum values, you want to store all the integers in between in an array, including these.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> arr = { 0, };
    int min = 2;
    int max = 8;
    int idx = 0;

    for (int i = min; i <= max; i++) {
        arr[idx++] = i;
    }

    std::cout << arr[0] << "\n";

    return 0;
}

Compiling the above code

main: malloc.c:2401: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed. Aborted (core dumped)

This error does not output the value of arr[0]. It's hard to even interpret the error message, how can I solve it?

c++ vector

2022-09-21 15:49

1 Answers

You created a vector with a size/capacity of 1 at the time of vector creation

I think it's because it's assigned by accessing the index outside the vector range (arr[idx++]) while going around the for door.

When you make an arr, you can know the size, so make it to secure space in advance.

std::vector<int> arr(max - min + 1);

Or how about using arr.push_back(value); instead of assigning the value with arr[idx] = value; for dynamic allocation?


2022-09-21 15:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.