繁体   English   中英

C会自动释放函数内部分配的内存吗?

[英]does C automatically free allocated memory inside a function?

我创建了以下函数来获取日期时间字符串:

char *GetDateTime (int Format)
{
    if (Format > 2) Format = 0;

    double  DateTimeNow;
    int     BufferLen;
    char    *DateTimeFormat [3] =   {   "%X %x" ,   //Time Date
                                        "%x"    ,   //Date
                                        "%X"    };  //Time
    char    *DateTimeBuffer = NULL;

                        GetCurrentDateTime      (&DateTimeNow);
    BufferLen       =   FormatDateTimeString    (DateTimeNow, DateTimeFormat [Format], NULL, 0);
    DateTimeBuffer  =   malloc                  (BufferLen + 1);
    FormatDateTimeString    (DateTimeNow, DateTimeFormat [Format], DateTimeBuffer, BufferLen + 1 );

    return DateTimeBuffer;
}

我不释放'DateTimeBuffer',因为我需要传递其内容。 我不知道那记忆是否会清除。 请帮忙。

它本身并不会清除。 您必须在调用程序函数中或在最后一次访问内存的地方调用free

例:

char *dateTimeBuffer = GetDateTime(1);
 .
 . 
 /*  do stuff with dateTimeBuffer */
 .
 .
 /* you don't need dateTimeBuffer anymore */
free(dateTimeBuffer);

每当使用malloc都必须手动free ,但是退出它所位于的作用域时,堆栈上分配的内存将自动清除,例如,在GetDateTime()函数中, DateTimeFormat将在该函数返回时自动清除。

在C语言中,没有任何事情会自动发生。 malloc每个对象,稍后都必须用free清除。 由于要从该函数返回DateTimeBuffer ,因此数据的接收者应处理该缓冲区,然后free它。 请务必对该功能进行彻底注释。

不,与每个分配区malloc应该明确地释放free ; 如果不这样做,可能会导致内存泄漏。 在大多数操作系统上,当进程终止时,将释放其所有地址空间(因此,如果不free内存,它将随其地址空间一起消失)

char    *DateTimeBuffer

这是该函数的局部指针。 因此,当您从函数返回时,分配的内存将不会被释放,除非您使用

free(DateTimeBuffer);

但是由于内存是在堆上分配的,因此您可以返回该函数外部仍然有效的位置的地址。 使用后分配的内存应使用free()显式释放

没有它不清晰。 malloc功能将从堆请求的内存块。 当不再需要时,必须将从malloc返回的指针传递给free函数,这会释放内存,以便可以将其用于其他目的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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