Fer*_*eak 1 c++ linux integer diskspace overflow
所以,我有以下代码,我知道它在某个地方被打破了,我根本无法确定...
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;
}
Run Code Online (Sandbox Code Playgroud)
当我编译它时,告诉我:
part_list.cpp: In function ‘uint64_t get_disk_total(const char*)’:
part_list.cpp:50:59: warning: integer overflow in expression [-Woverflow]
Run Code Online (Sandbox Code Playgroud)
好.当我运行它时,结果是(手动添加换行符):
total for [/] is:2900029440
block size (stfs.f_bsize):4096
block count (stfs.f_blocks):4902319
mul:2900029440
hardcoded: 18446744072314613760
Run Code Online (Sandbox Code Playgroud)
我知道,那4902319 * 4096 = 20079898624... 谷歌告诉我它是.因此,如何在地球上我得到先2900029440,然后18446744072314613760在同样的计算?有人可以解释一下这里发生了什么吗?它现在超出了我的综合能力,而且我觉得,这是一个隐藏在某个地方的微小问题... 4902319 * 4096对于像这样疯狂的应用来说,不应该是一个巨大的数字......
谢谢您的帮助!
小智 6
首先,您计算(4096 * 4902319)哪个被计算为int溢出.然后将该数字转换为uint64_t.
尝试:
(4096 * (uint64_t) 4902319)
Run Code Online (Sandbox Code Playgroud)
使其计算为uint64_t.