Search code examples
cstrftime

C strftime has ending hex characters


I am trying to add a Date header to my HTTP response. So far, I have been doing something like that:

char timebuf[37];
time_t now = time(0);
struct tm tm = *gmtime(&now);
strftime(timebuf, sizeof timebuf,"Date: %a, %d %b %Y %H:%M:%S %Z\r\n", &tm);)

However, when inspecting timebuf, I am, sometimes (like on the 1st request of the server), receiving a \x7f ending character.

Why is that inconsistent? I have double checked the size of timebuf and it should be exactly 37.


Solution

  • The format string you've shown us will result in a string of length 37. Excluding the NULL terminator.

    Your array should have 38 elements!

    Currently your timebuf is left unterminated, so you have undefined behaviour anywhere that expects a null-terminated string. That you're seeing \x7f sometimes and other characters sometimes (presumably even \0 sometimes) is just pure chance.


    From cppreference.com's C documentation on strftime:

    Converts the date and time information from a given calendar time time to a null-terminated multibyte character string str according to format string format. Up to count bytes are written.

    And here are some sums:

    Substr     Length
    ---------+--------
    "Date: "     6
    "%a"         3
    ", "         2
    "%d"         2
    " "          1
    "%b"         3
    " "          1
    "%Y"         4
    " "          1
    "%H"         2
    ":"          1
    "%M"         2
    ":"          1
    "%S"         2
    " "          1
    "%Z"         4
    "\r\n"       2
    
    NULL term.   1
    -----------------
             =   38