-1

For some reason when I insert n=99999999, I dont get the message "Not enough memory". The program stops running and I get the following error:

Process returned -1073741819 (0xC0000005)   execution time : 6.449 s

Why is this happening?

int i, j;
int **a=(int**)malloc(n*sizeof(int*));
if (**a==NULL){
    printf("Not enough memory\n");
    return 1;
}
for (i=0; i<n; i++) {
     a[i]=(int*)malloc(n*sizeof(int));
    if (**a==NULL){
        printf("Not enough memory\n");
        return 1;
    }
}
J...S
  • 5,079
  • 1
  • 20
  • 35
Shir K
  • 603
  • 5
  • 9
  • 10
    The test `if (**a==NULL){` should be `if (a==NULL){` and next one should be `if (a[i]==NULL){`. – P.P Feb 12 '18 at 16:09
  • 1
    Instead of an array of pointers to arrays it's often more efficient to allocate a singular one-dimensional array and emulate the two dimensional aspect using offset calculations. It's also a good idea to wrap up these allocations inside of functions that can neatly allocate or free structures of this sort. – tadman Feb 12 '18 at 16:27
  • [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Feb 13 '18 at 06:39

1 Answers1

1

Do

if (a==NULL){
    printf("Not enough memory\n");
    return 1;
}

instead of

if (**a==NULL){
    printf("Not enough memory\n");
    return 1;
}

because malloc() returns a pointer to the allocated memory if it was successful which is assigned to a (not **a or *a).

Also there's no need to cast the return value of malloc(). See this post.

And as P.P. pointed out, it's

a[i]=malloc(n*sizeof(int));
if (a[i]==NULL){
     printf("Not enough memory\n");
     return 1;
}

and not

a[i]=(int*)malloc(n*sizeof(int));
if (**a==NULL){
     printf("Not enough memory\n");
     return 1;
}

Edit: Note that the return value of malloc() needn't be explicitly cast in C. See this post.

J...S
  • 5,079
  • 1
  • 20
  • 35