CaTx
CaTx

Reputation: 1501

does C automatically free allocated memory inside a function?

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.

Upvotes: 3

Views: 4843

Answers (5)

Mooing Duck
Mooing Duck

Reputation: 66981

In C, nothing ever happens automatically. Every object you malloc, must later be cleared with a free. Since you're returning the DateTimeBuffer from the function, the receiver of the data should process the buffer, and then free it. Be sure to comment this thoroughly for the function.

Upvotes: 2

No, every zone allocated with malloc should be explicitly freed by free ; if you don't do that you might have a memory leak. On most OSes, when a process terminates, all its address space is released (so if you don't free memory, it would disappear with its address space)

Upvotes: 1

SVN
SVN

Reputation: 254

No it doesn't clear.The malloc function will request a block of memory from the heap . You have to pass the pointer returned form malloc to the free function when is no longer needed which deallocates the memory so that it can be used for other purposes.

Upvotes: 1

Gopi
Gopi

Reputation: 19874

char    *DateTimeBuffer

This is pointer local to the function. So when you return from the function the memory allocated will not be freed until you use

free(DateTimeBuffer);

But since the memory is allocated on heap you can return the address of the location which is still valid outside of the function. The memory allocated after being used should be freed explicitly using free()

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

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.

Upvotes: 6

Related Questions