3

我的 Spirit Qi 解析器经常遇到段错误。

在花了几天时间调试问题(我发现堆栈跟踪无法理解)后,我决定将其缩减为一个最小的示例。谁能告诉我做错了什么,如果有的话?

将代码保存为 bug.cpp,编译,g++ -Wall -o bug bug.cpp你应该很高兴。

//#define BOOST_SPIRIT_DEBUG_PRINT_SOME 80
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/version.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>

namespace /*anon*/
{
    using namespace boost::spirit::qi;

    template <typename Iterator, typename
        Skipper> struct bug_demo : 
            public grammar<Iterator, Skipper>
    {
        bug_demo() : 
            grammar<Iterator, Skipper>(story, "bug"),
            story(the),
            the("the")
        {
//          BOOST_SPIRIT_DEBUG_NODE(story);
//          BOOST_SPIRIT_DEBUG_NODE(the);
        }

        rule<Iterator, Skipper> story, the;
    };

    template <typename It>
        bool do_parse(It begin, It end)
    {
        bug_demo<It, space_type> grammar;
        return phrase_parse(begin, end, grammar, space);
    }
}

int main()
{
    std::cout << "Spirit version: " << std::hex << SPIRIT_VERSION << std::endl;

    try
    {
        std::string contents = "the lazy cow";
        if (do_parse(contents.begin(), contents.end()))
            return 0;
    } catch (std::exception e)
    {
        std::cerr << "exception: " << e.what() << std::endl;
    }
    return 255;
}

我已经测试过了

  • g++ 4.4、4.5、4.6 和
  • boost 版本 1.42 (ubuntu meerkat) 和 1.46.1.1 (natty)

输出是

sehe@meerkat:/tmp$ ./bug 
Spirit version: 2020
Segmentation fault

或者,使用 boost 1.46.1 它会报告Spirit version: 2042

4

1 回答 1

5

按照您在答案中的建议更改初始化顺序只会隐藏问题。实际问题是,它rule<>具有适当的 C++ 复制语义。您可以通过将语法初始化重写为:

bug_demo() : 
    grammar<Iterator, Skipper>(story, "bug"),
    story(the.alias()),
    the("the")
{}

有关基本原理和更详细的解释,请参见此处

于 2011-05-14T13:41:13.297 回答