简体   繁体   中英

Not enough memory

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;
    }
}

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 PP 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM