Freeing memory *after* returning from function.

It's been a while since I've used C, and I think I've coded myself into a corner.

(I could quite easily change the way I'm doing things to avoid this problem but it's now become academic matter for me :D )

I have a function which should return the date.

Code:
/** Get current date and time. */
char * 
get_time(void)
{
    time_t rawtime;
    struct tm * timeinfo;
    
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    
    char buffer[MAX_TIME_STRING];

    //char * buffer = malloc(MAX_TIME_STRING);
    
    strftime(buffer, MAX_TIME_STRING, "%c", timeinfo);

    return buffer;
}

Note the commented out line. This function works if I uncomment it but then I run into the problem of how to free memory after the function has returned!

What is the usual way to go about this? And by this I mean freeing memory but only after a function has returned?

inb4 Pass a pointer as an argument and write to that...
 
The usual way is "Pass a pointer as an argument and write to that". Alternatively, you can write your documentation for get_time that it is the caller's job to free the memory returned by the function.

This fails as written since the buffer is scoped only to the function (only allocated on the stack). Using the pointer to malloced memory (on the heap) you can pass it back.
 
Code:
/** Get current date and time. */
char * 
get_time(void)
{
    time_t rawtime;
    struct tm * timeinfo;
    
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    
    char buffer[MAX_TIME_STRING], *ret;
   
    strftime(buffer, MAX_TIME_STRING, "%c", timeinfo);

    ret = &buffer[0];

    return ret;
}
Give that a try. Since you are already allocating space for buffer, there is no reason to allocate more memory again. In my modifications, we return the address of your first array element. The only problem with this is if you are on a memory constrained device, and you need to malloc then free.
 
This is wrong, the pointer will be pointing to get_time()'s stack, meaning you should not refer to it after the function returns as its stack will be reclaimed and that memory used for something else or not(depends on many things). There are two ways to deal with this, either use malloc/mmap or pass pointer to get_time() by adding additional argument that could point to caller function's stack.
 
expl said:
This is wrong, the pointer will be pointing to get_time()'s stack, meaning you should not refer to it after the function returns as its stack will be reclaimed and that memory used for something else or not(depends on many things). There are two ways to deal with this, either use malloc/mmap or pass pointer to get_time() by adding additional argument that could point to caller function's stack.

Yes I guess that's true...(doh)
 
you could also declare `buffer` to be static, and have the calling context copying the returned string on it's own discretion.
 
Back
Top