如何在 C 中释放内存? [英] How do I free memory in C?

查看:22
本文介绍了如何在 C 中释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写的代码有很多 1 &二维数组.我收到错误:无法分配区域"我认为这是因为分配了太多内存.我使用malloc"和免费"功能,但我不确定我是否正确使用它们.也许你知道我在哪里可以看到关于 C 中内存管理的好例子?

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 "malloc" and "free" functions, but I'm not sure I'm using them correctly. Maybe you know where I could see good examples on memory management in C?

所以..我只是想让一个算法工作,现在这段代码只是一个又一个函数..

so.. I just trying to get one algorithm work and for now this code is just function after function..

//memory allocation for 1D arrays
buffer = malloc(num_items*sizeof(double));

//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));
    }
    
    //code
Window(N, window_buffer);
STFTforBMP(buffer,N,f, window_buffer);
getMagnitude(buffer,f, N, magnitude);
calculateEnergy(flux,magnitude, f);
calculateExpectedEnergy(expected_flux, candidate_beat_period, downbeat_location, f);
calculateCrossCorrelation(cross, flux, expected_values, f);
findLargestCrossCorrelation(&cross_max, cross, f);
normalizeCrossCorrelation(cross_norm, &cross_max, cross, f);
    ...............

我应该如何使用free 功能?

How should I use the free function?

推荐答案

您必须 free() 分配的内存与使用 malloc() 分配内存的顺序完全相反.

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.

一维数组的内存分配:

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

一维数组的内存释放:

    free(buffer);

二维数组的内存分配:

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

二维数组的内存释放:

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

    free(cross_norm);

这篇关于如何在 C 中释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆