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

CaT*_*aTx 3 c malloc free

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

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;
}
Run Code Online (Sandbox Code Playgroud)

我不释放“DateTimeBuffer”,因为我需要传递它的内容。我想知道那段记忆是否会自行清除。请帮忙。

Iha*_*imi 6

它本身并不清楚。您必须调用free调用者函数,或者最后一次访问内存的地方。

例子:

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

无论何时使用,malloc都必须free手动进行,但是当您退出它所在的作用域时,在堆栈上分配的内存会自动清除,例如在函数中,GetDateTime()DateTimeFormat函数返回时,会自动清除。