【问题标题】:How will you free the memory allocated?你将如何释放分配的内存?
【发布时间】:2015-07-30 19:44:13
【问题描述】:

我需要释放一些分配给我的程序的内存。我可以在需要的时候使用一些东西来清理内存吗?

#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4

int main()
{
    int **p, i, j;
    p = (int **) malloc(MAXROW * sizeof(int*));
    return 0;
}

【问题讨论】:

  • 不清楚你在问什么。要释放内存,只需调用free(p)。但如果你问的是 C 是否有原生垃圾回收,那么答案是否定的。
  • 对于一个新问题来说是一个明确的问题。不要害怕他@AlanAu 先生
  • 使用正确的类型,不要强制转换 malloc 的结果:int* (*p)[MAXROW] = malloc (MAXROW * sizeof(int*));.
  • @Lundin 以及在malloc(等)you should always write it 中以ptr = malloc(sizeof(*ptr) * ...); 而非ptr = malloc(sizeof(ptrtype*) * ...); 调用sizeof 时。
  • @Eregrith 只有将指针声明为数组指针时才会起作用。但是,您的建议是编码风格的主观问题,使用任何一种形式都没有明显的好处。这两种风格的争论我已经听过无数次了,无需重复。这两种风格都有合理的理由。只需记录您在编码风格指南中选择的那个。

标签: c malloc


【解决方案1】:

第 1 点

您无法释放一些内存。你必须释放所有。详细地说,通过单个调用malloc() 或家庭分配的任何内存,一次将是free-d。您不能释放 一半(左右)已分配的内存。

第 2 点

  • do not castmalloc()C 中的家人的返回值。
  • 您应该always write sizeof(*ptr) 而不是sizeof(type*)

第 3 点

您可以使用free() 来释放分配的内存。

例如,请参阅下面的代码,请注意内联 cmets

#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4

int main(void)                        //notice the signature of main
{
    int **p = NULL;                      //always initialize local variables
    int i = 0, j = 0;

    p = malloc(MAXROW * sizeof(*p));  // do not cast and use sizeof(*p)
    if (p)                            //continue only if malloc is a success
    {

        //do something
        //do something more

        free(p);                      //-----------> freeing the memory here.
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    这很简单。 您可以使用此代码来清理您唯一使用的变量。

    #include<stdio.h>
    #include<stdlib.h>
    #define MAXROW 3
    #define MAXCOL 4
    
    int main()
    {
         int **p, i, j;
         p = (int **) malloc(MAXROW * sizeof(int*)); 
         free(p);
         return 0;
    }
    

    【讨论】:

    • But you dont need it now cause your code is small....不好的建议。
    • 我的意思是对于这个程序,他不需要释放他的内存。它只有 2 行程序。我没有建议他买一个更大的。
    • 不,这不是正确的方法,恕我直言。你应该 free() 你分配的东西,不管 LoC。
    • 是的,我相信你现在是,但我只是认为那只是 2 行。非常感谢您的建议,我将再次对其进行编辑。
    • 看,我的意思是,不要让free()ing 动态分配的内存成为一项工作,让它成为一种习惯。从长远来看会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    相关资源
    最近更新 更多