Operating System: Windows 10 1909
MinGW-64: 8.1
I need to use regular expressions in my program to match some simple stuff. At first, I used std::regex, but I found that it crashed when running. It threw an exception.
std::string pattern = "[abc]";
try {
std::cout<<"111111111\n";
std::regex regexPattern(pattern);
std::cout<<"222222222\n";
std::smatch match;
if (std::regex_match(line, match, regexPattern)) {
...
}
} catch (const std::exception& e) {
std::cerr << "regex match error: " << e.what() << std::endl;
return false;
}An exception was thrown
111111111
regex match error: std::bad_alloc
It crashes immediately when creating a std::regex object. It doesn’t match anything at all.
Just like in the code before, I tested letting it match something simple like "[abc]" and it still crashes, but if I let it match something simple like "abc" without brackets, it runs—but that doesn’t really make any sense.
I even made a small program to test using std::regex, but it runs just fine.
#include <iostream>
#include <regex>
#include <string>
int main() {
try {
std::regex re("[abc]");
if (std::regex_search("a", re)) {
std::cout << "yes 1\n";
}
} catch (const std::exception& e) {
std::cout << "no 1" << e.what() << "\n";
}
try {
std::regex re("[a-z]");
if (std::regex_search("m", re)) {
std::cout << "yes 2\n";
}
} catch (const std::exception& e) {
std::cout << "no 2" << e.what() << "\n";
}
return 0;
}yes 1
yes 2
I don’t know why my program crashes, but the small snippet of code works just fine. I asked AI, and it said that this is a known serious bug in GCC libstdc’s std::regex. The regex implementation in libstdc has a lot of flaws. Some regular expressions will go into infinite recursion/infinite memory allocation when compiled, crazily requesting memory → std::bad_alloc, running out of memory and crashing.
But can something as simple as the regex "[abc]" really make std::regex crash?
In the end, I gave up on using std::regex and used an open-source library called slre for simple regex matching.