提升正则表达式运行时错误

5

我正在尝试使用我在另一台计算机上编写的代码,该代码将字符串分割成标记。这段代码可以正常编译。此外,在其他一些计算机上,代码也按预期工作。我已将代码简化为以下内容:

#include <string>
#include <boost/regex.hpp>

typedef std::vector<std::string> token_t ;

token_t generate_tokens(std::string raw_input){ 
//this function breaks a input string into tokens. So test 100 goes to 2 tokens "test" and "100".

    boost::regex re_splitter("\\s+"); //this uses the regex \s+ to find whitespace. The + finds one or more whitespace characters.

    boost::sregex_token_iterator iter(raw_input.begin(), raw_input.end(), re_splitter, -1);
    //this breaks the string using the regex re_splitter to split into tokens when that is found. 
    boost::sregex_token_iterator j; //This is actually in the Boost examples, j is the equivalent of end. Yes this did also seem weird to me at first...

    token_t token_vector;
    unsigned int count = 0;
    while(iter != j)
    {
        token_vector.push_back(*iter);
        std::cout << *iter++ << std::endl;
        ++count;
    }
    return token_vector;
}

int main(){
    std::string in;
    int amount = -1;

    std::cout << "action: ";
    std::getline(std::cin, in);

    boost::regex EXPR("^test \\d*(\\.\\d{1,2})?$");
    bool format_matches = boost::regex_match(in, EXPR);

    token_t tokens = generate_tokens(in);

    if(format_matches){
        amount = atoi(tokens.at(1).c_str());
    }
    std::cout << "amount: " << amount << "\n";
    return 0;
}

这段代码可以通过以下命令编译而无错误或警告: g++ -Wall test.cpp -lboost_regex,但是当提供输入test 100时,程序会崩溃。

操作: test 100

a.out: /usr/local/include/boost/smart_ptr/shared_ptr.hpp:412: typename boost::detail::shared_ptr_traits::reference boost::shared_ptr::operator*() const [with T = boost::regex_traits_wrapper > >]: Assertion `px != 0' failed.

已中止

我完全不知道发生了什么。这是我的代码还是库的问题?非常感谢任何有关调试此问题的建议!

1
你使用的是哪个版本的boost?那段代码和输入在MSVC 2010 SP1和Boost 1.46.1下运行良好。 - ildjarn
4个回答

8

这不是一个 bug,而是 Boost 标头文件的冲突问题。

可能是因为文件引用错误,或者库引用错误(regex 模块是少数需要编译的 Boost 模块之一)。

您应该通过使用 -l 和 -I 开关确保使用了正确的文件,例如:

   g++ -W -Wall main.cpp $(LDFLAGS) -lboost_regex -I/data1/PROJECT_SEARCH/libsrc/boost_1_46_1

4

当您使用boost的一个版本进行编译,但使用另一个版本进行执行时,就会出现这种情况。您应该检查所安装的boost库版本以供执行,以及您用于编译的版本。


0

在gdb或类似程序中运行此代码,在这些部分的开头设置断点,然后逐步执行,直到找到有问题的代码行。

您遇到的错误看起来像是在某个地方将无效指针传递给了boost库。


-1

既然你的代码中没有使用shared_ptr,而且我也看不出其他有问题的地方,并且它在其他机器上运行正常,我猜测这可能是Boost.Regex中的一个bug。

我敢打赌其他机器上安装了其他版本的boost库?

如果我要猜的话,我会先尝试修改std::cout << *iter++ << std::endl;这一行代码。改为:std::cout << *iter << std::endl; ++iter;

另外,像Swiss建议的那样,在调试器中运行它,看看断言是在哪里触发的。


我按照建议进行了更改,但仍然遇到了完全相同的问题。 - shuttle87
好的,这只是一个猜测。正如Swiss和我已经建议的那样:启动gdb(或任何其他调试器),看看assert()是在哪里触发的。然后从那里开始解决问题。如果这是Boost.Regex中的一个错误,你应该检查最新版本(我想是1.46)是否仍然存在,并且如果是的话,提交一个错误报告。 - Paul Groke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接