Search code examples
c++sigabrt

How to prevent SIGABRT from occuring when allocating an array of integers?


I'm testing a very basic implementation of a heap by adding and deleting a lot (50k) random elements to it. However I never get to remove elements, as a SIGABRT occurs.

I've tried to initialize an array of integers with zeroes, but that didn't help.

int Heap::pop() {
if (size == 0) {
    std::cerr << "The heap is empty.\n";
    return 0;
}
if(size == 1){
    int key = heap[0];
    heap = new int[0];
    size = 0;
    return key;
}
else {
    int key = heap[0];

    int *temp;
    temp = heap;
    temp[0] = temp[size - 1];
    heap = new int[size - 1]; //GDB marks this line
    for (int i = 0; i < size - 1; i++)
        heap[i] = temp[i];

    heapifyDown(0);

    size--;
    return key;
}
}

It seems it fails when it's about to initialize an array of size 49992.


Solution

  • You never deallocate the memory that you allocate with new. You will therefore eventually run out of heap space if your code runs long enough, at which point further allocations will fail (as GDB shows).

    In the snippet you have shown, all that is missing is a delete[] temp; after the loop that copies the data. But these errors are easily avoided by using the standard library containers (such as std::vector) which do all of this for you.