C26451:使用运算符'+'对4字节值进行算术溢出,然后将结果转换为8字节值

问题描述 投票:0回答:1

我正在尝试编写一个使用两种不同的字符串搜索算法来搜索电影脚本的程序。但是,警告C26451:在4字节值上使用运算符'+'进行算术溢出,然后将结果转换为8字节值继续出现在rabin karp的计算哈希部分中,是否有解决方法?任何帮助将不胜感激。

#define d 256
Position rabinkarp(const string& pat, const string& text) {

    int M = pat.size();
    int N = text.size();
    int i, j;
    int p = 0; // hash value for pattern  
    int t = 0; // hash value for txt  
    int h = 1;
int q = 101;
    // The value of h would be "pow(d, M-1)%q"  
    for (i = 0; i < M - 1; i++)
        h = (h * d) % q;

    // Calculate the hash value of pattern and first  
    // window of text  
    for (i = 0; i < M; i++)
    {
        p = (d * p + pat[i]) % q;
        t = (d * t + text[i]) % q;
    }

    // Slide the pattern over text one by one  
    for (i = 0; i <= N - M; i++)
    {

        // Check the hash values of current window of text  
        // and pattern. If the hash values match then only  
        // check for characters on by one  
        if (p == t)
        {
            /* Check for characters one by one */
            for (j = 0; j < M; j++)
            {
                if (text[i + j] != pat[j])
                    break;
            }

            // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]  
            if (j == M)

            return i;
        }

        // Calculate hash value for next window of text: Remove  
        // leading digit, add trailing digit  
        if (i < N - M)
        {
            t = (d * (t - text[i] * h) + text[i + M]) % q;//   <---- warning is here 

[i + M


            // We might get negative value of t, converting it  
            // to positive  
            if (t < 0)
                t = (t + q);
        }
    }

    return -1;
}

context for the error

c++ hash overflow rabin-karp
1个回答
1
投票

您要添加两个int,在您的情况下为4个字节,而std::string::size_type在您的情况下可能为8个字节。当您这样做时,就会发生上述转换:

 text[i + M]

这是一个以std::string::operator[]作为参数的对std::string::operator[]的调用。

使用std::string::size_type,通常与std::string::size_type相同。

即使使用size_t,gcc也不会对此发出任何警告,所以我想您实际上已激活了所有可能的警告,或类似的东西

© www.soinside.com 2019 - 2024. All rights reserved.