Summit
Summit

Reputation: 2268

std::strftime crashes with incorrect input

This is how i am using the function to extract date and time.

std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));

but if the format text is not formatted properly the application crashes like

std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), "%Y-%m-%d %:%M:%S", std::localtime(&now));

How can i stop the application from crashing if the format text is not correct ?

Upvotes: 1

Views: 631

Answers (1)

MihanEntalpo
MihanEntalpo

Reputation: 2052

It seems, that you are taking format string from outwhere, maybe from user input.

So as you cannot make your strftime not crash, you have to validate format string before you call strftime.

For example, you can:

  1. Use regular expressions to find all sequences like
    "%[^aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%]"
    (format letters are taken from here: http://www.cplusplus.com/reference/ctime/strftime/)

  2. If you've found such a substring you just don't run strftime and give your user error message like "Error! Incorrect input!" and maybe location of the error in format string.

for that you can use regex_match from std lib http://www.cplusplus.com/reference/regex/basic_regex/basic_regex/

#include <regex>
#include <string>
...
// defining regex pattern:
std::string pattern = "%[^aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%]";
...
// user_format - is a variable with possible wrong date format
// if regexp didn't match then...
if (! std::regex_match (user_format, std::regex(pattern)))
{
    // run your code!
    std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), user_format, std::localtime(&now));
}
else
{
    // lets pretend returning false means an error
    return false;
}

Maybe this example not covers all the cases it's just a draft. But I think you get the idea. Also, it'll be nice to have a function like "validate_date_format" to use it everywhere in your programm with convinience

Upvotes: 2

Related Questions