Is there any better solution to avoid my "memory exceeded" error in hackerearth

Viewed 492
int **list, **short_list;
//num defines the number of rows and 2 defines no. of column needed
list = malloc(num * 2 * sizeof(int *));
short_list = malloc(num * 2 * sizeof(int *));

for(i = 0; i < num; i++){
    list[i] = malloc(num * 2 * sizeof(int));
    short_list[i] = malloc(num * 2 * sizeof(int));
}

Though I have created dynamic memory allocation using pointers to array, undergone "Memory Limit exceeded" error to few of my outputs in hackerearth. Is this way of memory allocation is wrong.

1 Answers

There is something wrong with your allocation. In the first malloc you get num * 2 pointers but in the loop you only initialize num of these pointers. That is for sure a bug.

Further it seems strange that you inside the loop uses num * 2 again. That means you end up allocating num * num * 2 integers. That is most likely not what you want.

If you really want the matrices to be num * 2 simply do:

int **list, **short_list;
//num defines the number of rows and 2 defines no. of column needed

list = malloc(num * sizeof(int *));            // Only use num here
short_list = malloc(num * sizeof(int *));

for(i = 0; i < num; i++){               
    list[i] = malloc(2 * sizeof(int));         // Only use 2 here
    short_list[i] = malloc(2 * sizeof(int));
}

Another and simpler way to allocate a num * 2 matrix is:

int (*list)[2];
list = malloc(num * sizeof *list);
Related