Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does C automatically free allocated memory inside a function?

Tags:

c

malloc

free

I created the following function to get Date Time string:

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;
}

I do not free 'DateTimeBuffer' because I need to pass out its content. I wonder if that memory clears itself. Please help.

like image 388
CaTx Avatar asked Jan 01 '26 21:01

CaTx


1 Answers

It doesn't clear itself. You have to call free in the caller function, or wherever the last access to the memory happens.

Example:

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

Whenever you use malloc you must free manually, but memory allocated on the stack is automatically cleared when you exit the scope in which it lives, for instance in your GetDateTime() function DateTimeFormat will be automatically cleared when the function returns.

like image 198
Iharob Al Asimi Avatar answered Jan 03 '26 10:01

Iharob Al Asimi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!