Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of std::strftime

Tags:

I think I read somewhere that if I pass a nullptr to std::strftime, the function would return the required buffer size. And indeed, the following code works perfectly well on numerous linux systems I've tried it on (not when compiled with VS though):

#include <iostream>
#include <ctime>
#include <string>

int main()
{
    std::time_t time{};
    std::tm const * ltime = std::localtime(&time);

    const char * formatString = "%Y-%b-%d";
    //allocate buffer of appropriate size
    auto requiredSize = 1 + std::strftime(nullptr, 50, formatString, ltime);
    std::cout << "Required buffer size:" << requiredSize << "\n";

    //Format time to string
    std::string buff(requiredSize, ' ');
    std::strftime(&buff[0], requiredSize, formatString, ltime);

    std::cout << buff << std::endl;
}

However, I was unable to find my original source or any other documentation that would specify this behavior. So my question is:

  • On which systems / compilers / standard library implementations (if any) is this a guaranteed behavior?
  • Where can I find the according documentation?

Edit: I added the C label, as I've seen the same result with equivalent C code and at least with gcc/g++ (or rather glibc/libstdc++) std::strftime is probably just an alias for the c-function strftime anyway.

like image 925
MikeMB Avatar asked Aug 24 '16 19:08

MikeMB


1 Answers

As far as I can tell and as others have wrote in the comments, above code is most probably undefined behavior according to the ISO C or C++ standard and as far as my own experiments are concerned will crash when compiled with VS2015.

However, as far as glibc is concerned, @rici was spot on:

From the documentation of The GNU C Library:

If s is a null pointer, strftime does not actually write anything, but instead returns the number of characters it would have written.

like image 149
MikeMB Avatar answered Sep 26 '22 16:09

MikeMB