0

I am facing to an issue when I want to allocate a memory for a problem of size n = 32678 a 2D array of size tab[2n][n+1]. This is a code :

#include <stdio.h>
#include <stdlib.h>

int main(){
    int n = 32768;
    unsigned int** tab = (unsigned int**) malloc(2 * n * sizeof * tab);
    if(tab == NULL){
        printf("insuffisant memory\n");
        exit(EXIT_FAILURE);
    }
    tab[0] = (unsigned int*) malloc(2 * n * (n+1) * sizeof * tab[0]);
    if(tab[0] == NULL){
        printf("insuffisant memory\n");
        exit(EXIT_FAILURE);
    }
    for(int i = 1; i < 2 * n; i++)
        tab[i] = tab[0] + i * (n+1);
    tab[2*n - 1][0] = 0;

}

The last instruction end up to an error:

Segmentation fault (core dumped)

I don't understand what happen because I don't have problem when n = 1 to 32767. From n = 32768 I have this error.

Please do you understand what happen?

Compiii
  • 1
  • 1
  • What is `sizeof int` on your platform? `2 * n * (n+1)` could be a problem for `n = 32768`. I would suggest to try `malloc((size_t)2 * n * (n+1) * sizeof * tab[0])`. – Osiris Jan 07 '20 at 09:14
  • 1
    Your allocation is not for `[2n][n+1]`. Also, this is not a 2D array. You might want to be [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) instead. I suspect that allocating the memory correctly will have much a greater performance impact than parallelization. You should have something like `unsigned int (*tab) [n] = malloc( sizeof (unsigned int[2*n][n+1]) );` instead, as explained in that link. – Lundin Jan 07 '20 at 10:34
  • @Osiris in my platform the `sizeof int` is 4 and `sizeof int*` is 8. I tried your suggest and it is not worked. Thank you! – Compiii Jan 07 '20 at 11:43
  • @Lundin thank you for your answer. You are wright! It works well now! – Compiii Jan 07 '20 at 14:37

0 Answers0