【问题标题】:C26451: Arithmetic overflow using operator '+' on a 4 byte value then casting the result to 8 byte valueC26451:在 4 字节值上使用运算符“+”算术溢出,然后将结果转换为 8 字节值
【发布时间】:2020-06-19 11:44:18
【问题描述】:

我正在尝试编写一个程序,该程序使用两种不同的字符串搜索算法搜索电影脚本。但是警告 C26451: Arithmetic overflow using operator '+' on a 4 byte value then cast the result to 8 byte value 不断出现在 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

【问题讨论】:

  • 请在问题中发布错误/警告,而不是截图
  • @1201 d 在最顶端是#define d 256。希望它们都是具有更具描述性的名称的大写字母,但我们到了。

标签: c++ hash overflow rabin-karp


【解决方案1】:

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

 text[i + M]

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

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

gcc 没有给出任何警告,即使是-Wall -Wextra -pedantic,所以我猜你真的激活了所有警告,或者类似的东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多