一个安全的蓄电池真的这么复杂吗?

Mar*_*tin 0 c c++ integer-overflow undefined-behavior

我正在尝试编写一个在不受约束的输入下表现良好的累加器.这似乎不是微不足道的,需要一些非常严格的计划.这真的很难吗?

int naive_accumulator(unsigned int max,
                      unsigned int *accumulator,
                      unsigned int amount) {
    if(*accumulator + amount >= max) {
        return 1; // could overflow
    }

    *accumulator += max; // could overflow

    return 0;
}

int safe_accumulator(unsigned int max,
                     unsigned int *accumulator,
                     unsigned int amount) {
    // if amount >= max, then certainly *accumulator + amount >= max
    if(amount >= max) {
        return 1;
    }

    // based on the comparison above, max - amount is defined
    // but *accumulator + amount might not be
    if(*accumulator >= max - amount) {
        return 1;
    }

    // based on the comparison above, *accumulator + amount is defined
    // and *accumulator + amount < max
    *accumulator += amount;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我删除了样式偏见

M.M*_*M.M 5

你有没有考虑过:

if ( max - *accumulator < amount )
    return 1;

*accumulator += amount;
return 0;
Run Code Online (Sandbox Code Playgroud)

通过在"天真"版本中更改第一次比较的方向,可以避免溢出,即查看剩余多少空间(安全)并将其与要添加的数量(也是安全的)进行比较.

该版本假定在调用函数时*accumulator从未超过max; 如果你想支持这种情况,那么你必须添加一个额外的测试.