首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安全蓄电池真的这么复杂吗?

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

Stack Overflow用户
提问于 2014-08-19 22:17:45
回答 1查看 137关注 0票数 0

我正在尝试编写一个累加器,它在无约束输入的情况下表现良好。这似乎并不琐碎,需要一些相当严格的计划。真的这么难吗?

代码语言:javascript
复制
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;
}

编辑:我已经删除了风格偏见。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-19 22:24:12

你有否考虑过:

代码语言:javascript
复制
if ( max - *accumulator < amount )
    return 1;

*accumulator += amount;
return 0;

通过在“朴素”版本中更改第一个比较的方向,可以避免溢出,即查看还剩多少空间(安全),并将其与要添加的金额进行比较(也是安全的)。

此版本假设在调用函数时*accumulator从未超过max;如果要支持这种情况,则必须添加额外的测试。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25393881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档