代码仅在VC ++ 2015上的Release配置中产生堆栈溢出异常

时间:2017-02-28 14:50:25

标签: c++ visual-c++ crash stack-overflow

此代码在VC++ 2015 Debug配置中工作正常......但是它总是在Release中抛出堆栈溢出异常。特别是当启用代码优化“/ O2”时..

当我深入研究这个问题时......我发现编译器正在重用下一行中的第一个Sequence对象(x >> x).Check(&j);

我无法弄清楚问题是什么......以及如何避免这种行为

typedef char Char;

class TokenizerInterface
{
public:
    virtual bool Check(Char**) = 0;
}; 

class RulesSet : public TokenizerInterface
{
    TokenizerInterface& tok;
    public:

    RulesSet(TokenizerInterface& tok) : tok(tok) {}

    virtual bool Check(Char** x)
    {
        return tok.Check(x);
    }
};

class Sequence : public TokenizerInterface
{
private:
    TokenizerInterface& vtok1;
    TokenizerInterface& vtok2;

public:
    Sequence(TokenizerInterface& tok1, TokenizerInterface& tok2) :vtok1(tok1), vtok2(tok2) {}
    virtual bool Check(Char** x)
    {
        Char* start = *x;

        if (!vtok1.Check(&start) || !vtok2.Check(&start))
            return false;

        *x = start;
        return true;
    }
};


class In : public TokenizerInterface
{
private:
    Char* str;
public:
    explicit In(Char* str) : str(str) {}
    virtual bool Check(Char** x)
    {
        if (strchr(str, **x) != 0)
        {
            (*x)++;
            return true;
        }
        return false;
    }
};

inline Sequence operator >> (TokenizerInterface& t1, TokenizerInterface& t2)
{
    return Sequence(t1, t2);
}

int main()
{

    char* j = "OSOS";

    RulesSet x = In("O") >> In("S");
    (x >> x).Check(&j);//<<CRASH

    return 0;
}

0 个答案:

没有答案