partida
partida

Reputation: 501

simple C++ regex got run-time error in OSX but windows

This is the code:

#include <iostream>
#include <regex>
using namespace std;

int main() 
{
    string str = "hello_2019";
    regex pattern[2];
    memset(pattern, 0, sizeof(regex) * 2);
    pattern[0] = regex(".*_\\d+");
    pattern[1] = regex("[a-z]+_.*");
    for (int i = 0; i < 2; i++)
        cout << regex_match(str, pattern[i]) << endl;
    return 1;
}

enter image description here

But same code in OSX can't run:

enter image description here

Even using g++ can compile it, it results the run-time error.

g++ main.cpp
./a.out

1 11669 segmentation fault ./a.out

Upvotes: 0

Views: 145

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35454

This line:

memset(pattern, 0, sizeof(regex) * 2);

corrupts each of the regex objects in the pattern array.

Do not use memset to initialize non-POD objects such as regex. Using memset here leads to undefined behavior.

The simplest solution is to just remove that line. The array itself automatically default initializes the regex entries, so there is no need to (faultily) attempt to "zero-initialize" a regex object.

Upvotes: 3

Related Questions