How do I free memory in C?

后端 未结 2 916
灰色年华
灰色年华 2020-12-01 09:34

I\'m writing code which has a lot of 1 & 2 dimensional arrays. I got \"error: can\'t allocate region\" and I think its because too much memory is allocated. I use \"mall

2条回答
  •  一向
    一向 (楼主)
    2020-12-01 10:01

    You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

    Note that You should free the memory only after you are done with your usage of the allocated pointers.

    memory allocation for 1D arrays:

        buffer = malloc(num_items*sizeof(double));
    

    memory deallocation for 1D arrays:

        free(buffer);
    

    memory allocation for 2D arrays:

        double **cross_norm=(double**)malloc(150 * sizeof(double *));
        for(i=0; i<150;i++)
        {
            cross_norm[i]=(double*)malloc(num_items*sizeof(double));
        }
    

    memory deallocation for 2D arrays:

        for(i=0; i<150;i++)
        {
            free(cross_norm[i]);
        }
    
        free(cross_norm);
    

提交回复
热议问题