lundi 24 octobre 2022

How to resize dynamically allocated array of std::list?

I created a dynamically allocated array of lists of size 7 which works fine and elements can be pushed to each list in the array. But, when I try to resize the array to size 10 using realloc, which seems to give no error, but when I try to push elements to the lists, I get Segmentation fault error.

Code:

#include <iostream>
#include <list>

int main()
{
    std::list<int> *slots = new std::list<int>[7];

    for (int i = 0; i < 7; ++i)
    {
        slots[i].push_back(i + 1);
        slots[i].push_back(i + 2);
    }

    for (int i = 0; i < 7; ++i)
    {
        for (const auto &slot : slots[i])
        {
            std::cout << slot << ' ';
        }

        std::cout << '\n';
    }

    slots = (std::list<int> *)realloc(slots, sizeof(std::list<int>) * 10);

    // Segmentation fault
    for (int i = 0; i < 10; ++i)
    {
        slots[i].push_back(i);
    }

    return 0;
}

OUtput:

1 2 
2 3
3 4
4 5
5 6
6 7
7 8
Segmentation fault

How to fix this? Thanks.

Aucun commentaire:

Enregistrer un commentaire