Search code examples
c++segmentation-faultmallocdynamic-memory-allocation

Segmentation fault after 2-d array allocation


I have this code:

#include <iostream>
#include <math.h>

int main()
{
    int n,m,k,hours;
    std::cin >> n >> m >> k;
    hours = std::ceil(n * k / (float)m);
    int* checkers = new int[m];
    int** check = new int*[hours];
    for(int i(0); i < hours; i++)
        check[i] = new int[n];
    for(int i(0); i < n; i++)
        checkers[i] = (i + 1) % m;
    std::cout << check[0][0];

    return 0;
}

With specific input data like 20 4 1, it returns Segmentation Fault when I'm trying to print check[0][0]. But if I replace int* checkers = new int[m]; like this:

#include <iostream>
#include <math.h>

int main()
{
    int n,m,k,hours;
    std::cin >> n >> m >> k;
    hours = std::ceil(n * k / (float)m);
    int** check = new int*[hours];
    for(int i(0); i < hours; i++)
        check[i] = new int[n];
    int* checkers = new int[m];
    for(int i(0); i < n; i++)
        checkers[i] = (i + 1) % m;
    std::cout << check[0][0];

    return 0;
}

It will return malloc.c:2394: 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.

How can I fix it?

P.S. With input, for example 3 1 1, everything is alright.


Solution

  • You allocated m elements for checkers while using n elements.

    The number of elements to allocate and use should be matched (allocate n elements or use m elements, according to what you want to do).

    Also note that the contents of new int[n] are not automatically initialized, so you cannot rely on the value of check[0][0].