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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With