有趣且真烦人的整数问题

时间:2013-03-18 10:04:00

标签: c++ linux integer overflow diskspace

所以,我有以下代码,我知道它在某个地方被破坏了,我根本无法识别...

static uint64_t get_disk_total(const char* path)
{
    struct statvfs stfs;
    if ( statvfs(path, &stfs) == -1 )
    {
        return 0;
    }
    uint64_t t = stfs.f_blocks * stfs.f_bsize;
    std::cout  << "total for [" << path << "] is:" << t 
               << " block size (stfs.f_bsize):" <<   stfs.f_bsize
               << " block count (stfs.f_blocks):" << stfs.f_blocks 
               << " mul:" << stfs.f_blocks * stfs.f_bsize
               << " hardcoded: " << (uint64_t)(4096 * 4902319)     // line 50
               <<  std::endl ;
    return t;
}

当我编译它时,告诉我:

part_list.cpp: In function ‘uint64_t get_disk_total(const char*)’:
part_list.cpp:50:59: warning: integer overflow in expression [-Woverflow]

好。当我运行它时,结果是(手动添加换行符):

total for [/] is:2900029440 
block size (stfs.f_bsize):4096 
block count (stfs.f_blocks):4902319 
mul:2900029440 
hardcoded: 18446744072314613760

我知道,4902319 * 4096 = 20079898624 ... google告诉我它是。那么我是如何首先获得2900029440然后18446744072314613760进行同样的计算呢?有人可以解释一下这里发生了什么吗?它现在超出了我的综合能力,而且我觉得,这是一个隐藏在某个地方的微小问题... 4902319 * 4096不应该是一个如此巨大的数字,让应用程序像这样发疯......

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

首先计算(4096 * 4902319),计算为int并溢出。 然后该数字将转换为uint64_t

尝试:

(4096 *  (uint64_t) 4902319) 

使其计算为uint64_t。

答案 1 :(得分:1)

使用无符号长long 文字:

   4096 * 4902319ULL
                 ~~~

在计算溢出之前。

相关问题