什么是用C size_t类型的malloc参数的限制?文档说它UINT_MAX的上限,但我不能超越INT_MAX [英] What is the limit on malloc parameter of type size_t in C? Docs say it has an upper limit of UINT_MAX but I can't go beyond INT_MAX
问题描述
我想分配一个2.9GB字符数组
I want to allocate a 2.9GB char array with
database = (char*) malloc((2900 * 1000000 * sizeof(char)));
这给出了一个整数溢出警告和的malloc
收益 NULL
。该的malloc
参数的类型为为size_t
根据文档是类型 unsigned int类型
。
This gives an integer overflow warning and the malloc
returns NULL
. The
malloc
parameter is of type size_t
which according to documentation is of type
unsigned int
.
所以,最高应 UINT_MAX
这至少是2.9GB。然而,如果
我多试 MAX_INT
的的malloc
未能分配更多。这是否意味着为size_t
我的系统上是int类型?如何检查呢?我通过
So the max should be UINT_MAX
which is at least 2.9GB. However, if
I try to allocate more than MAX_INT
the malloc
fails. Does this mean
size_t
on my system is of type int? How do I check this? I looked through
/usr/include/stdlib.h
和
./lib/gcc/x86_64-redhat-linux/4.1.1/include/stddef.h
但
无法找到为size_t
的定义。非常感谢
推荐答案
有两个问题在这里。
一,溢出警告:无论 2900
和百万
的类型为 INT
,所以相乘的结果也是类型 INT
。结果不能再由32位有符号整数psented $ P $,所以它溢出。你需要投一个(或两个)参数为size_t
使用无符号运算。
First, the overflow warning: both 2900
and 1000000
are of type int
, so the result of multiplying them is also of type int
. The result cannot be represented by a 32-bit signed integer, so it overflows. You need to cast one (or both) arguments to size_t
to use unsigned arithmetic.
(或者,您可以移动的sizeof(char)的
是前两个术语之一,因为它的类型是为size_t
,虽然你也可以只删除的sizeof(char)的
,因为它始终是 1
)
(Or, you could move the sizeof(char)
to be one of the first two terms, since its type is size_t
, though you can also just remove the sizeof(char)
since it is always 1
.)
第二, malloc的最大尺寸
可以分配都取决于你所运行的平台上和程序的当前状态。如果没有足够的连续的地址空间留下来满足请求,显然的malloc
将失败。
Second, the maximum size that malloc
can allocate depends both on the platform on which you are running and on the current state of the program. If there is insufficient contiguous address space left to satisfy the request, obviously the malloc
will fail.
此外,在其上运行的平台上可能有一个对象多大可以动态分配的上限。您需要咨询您的平台的文档,以找出上限是什么。
Further, the platform on which you are running may have an upper limit on how large an object it can dynamically allocate. You'll need to consult your platform's documentation to find out what that upper limit is.
为size_t
肯定是不 INT
,因为 INT
始终签名和为size_t
始终是无。
size_t
is certainly not int
, because int
is always signed and size_t
is always unsigned.
这篇关于什么是用C size_t类型的malloc参数的限制?文档说它UINT_MAX的上限,但我不能超越INT_MAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!