ctime() return a string, why we don't need to free() this string' s memory?
Asked Answered
R

3

17

the prototype of the function ctime is

char *ctime(const time_t *timep);

As we can see, it return a string. but, where the sting be contained?

and why we shouldn't free the string's memory

This is sample code will get a lots of error message

char *p;
p = ctime(...);
...
free(p);

*** glibc detected *** ./a.out: free(): invalid pointer: 0x00007f0b365b4e60 ***

Reasoning answered 29/6, 2012 at 7:29 Comment(0)
C
17

It returns a pointer to a static buffer, and must not be free()d. From man ctime:

The four functions asctime(), ctime(), gmtime() and localtime() return a pointer to static data and hence are not thread-safe.

The C99 standard, section 7.23.3.2 The ctime function states that calling ctime(timer) function is equivalent to asctime(localtime(timer)), and the asctime() implementation (as illustrated in the same document) is equivalent to:

char *asctime(const struct tm *timeptr)
{
    static const char wday_name[7][3] = {
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
    };

    static const char mon_name[12][3] = {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };

    static char result[26];
    sprintf(result,
            "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
            wday_name[timeptr->tm_wday],
            mon_name[timeptr->tm_mon],
            timeptr->tm_mday, timeptr->tm_hour,
            timeptr->tm_min, timeptr->tm_sec,
            1900 + timeptr->tm_year);

    return result;
}

The argument passed to free() must be a pointer returned by a call to malloc(), calloc() or realloc() only, otherwise the behaviour is undefined.

Cherubini answered 29/6, 2012 at 7:34 Comment(5)
Just adding that if you want a thread-safe version, use ctime_r() instead.Golgi
@Turix, yep it states that on the linked page.Cherubini
I really think those arrays are [][4] (or, even better, pointer arrays to avoid this bug).Kordofanian
So, its allocating in global memory. Won't that be filled out when we call the function again and again?Smaragdite
@Smaragdite Yes, it would be best to copy the data from the static memory immediately following the call.Veronikaveronike
W
2

It points to static data and wasn't malloc'd.

Wake answered 29/6, 2012 at 7:33 Comment(0)
P
0

Your pointer p was not dynamically allocated with malloc or calloc, so you didn't ask for heap memory to be freed.

Your p is just a regular pointer pointing to some memory which was previously allocated (so available for you).

The variable that you give to ctime() should be created somewhere else and the creator of that variable is the owner of the resource borrowed to your pointer p, so your pointer is just an observer, not a resource owner, so there's nothing to be freed from your pointer.

Perfumer answered 2/11, 2023 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.