60

在 64 位系统上,sizeof(unsigned long)取决于系统实现的数据模型,例如 LLP64(Windows)上是 4 个字节,LP64(Linux 等)上是 8 个字节。sizeof(size_t)应该是什么?它是否像数据模型一样因数据模型而异sizeof(long)?如果是这样,怎么做?


参考:

维基百科上的 64 位数据模型

4

4 回答 4

64

size_t 由 C 标准定义为 sizeof 运算符 (C99 6.3.5.4.4) 的无符号整数返回类型,以及 malloc 和朋友 (C99 7.20.3.3 等) 的参数。实际范围设置为最大值 (SIZE_MAX) 至少为 65535 (C99 7.18.3.2)。

但是,这并不能让我们确定 sizeof(size_t)。该实现可以自由地使用它喜欢的任何 size_t 表示形式——因此大小没有上限——并且该实现也可以自由地将一个字节定义为 16 位,在这种情况下 size_t 可以等效于 unsigned char。

然而,撇开这一点不谈,一般来说,无论数据模型如何,32 位程序都有 32 位 size_t,64 位程序有 64 位。一般数据模型只影响静态数据;例如,在 GCC 中:

`-mcmodel=small'
     Generate code for the small code model: the program and its
     symbols must be linked in the lower 2 GB of the address space.
     Pointers are 64 bits.  Programs can be statically or dynamically
     linked.  This is the default code model.

`-mcmodel=kernel'
     Generate code for the kernel code model.  The kernel runs in the
     negative 2 GB of the address space.  This model has to be used for
     Linux kernel code.

`-mcmodel=medium'
     Generate code for the medium model: The program is linked in the
     lower 2 GB of the address space but symbols can be located
     anywhere in the address space.  Programs can be statically or
     dynamically linked, but building of shared libraries are not
     supported with the medium model.

`-mcmodel=large'
     Generate code for the large model: This model makes no assumptions
     about addresses and sizes of sections.

您会注意到指针在所有情况下都是 64 位的。毕竟,拥有 64 位指针而不是 64 位大小毫无意义。

于 2009-05-28T02:13:59.563 回答
15

它应该随架构而变化,因为它代表任何对象的大小。所以在 32 位系统size_t上可能至少有 32 位宽。在 64 位系统上,它可能至少为 64 位宽。

于 2009-05-28T01:32:18.290 回答
4

size_t 通常在 64 位机器上为 64 位

于 2009-05-28T01:35:36.410 回答
3

编辑:感谢您的评论-我在C99 标准中查找了它,该标准在第 6.5.3.4 节中说:

结果的值是实现定义的,它的类型(无符号整数类型)是size_t,定义在<stddef.h>(和其他头文件)

因此,size_t没有指定大小,只是它必须是无符号整数类型。但是,可以在标准的第 7.18.3 章中找到一个有趣的规范:

限制size_t

SIZE_MAX 65535

这基本上意味着,无论 的大小如何size_t,允许的值范围是 0-65535,其余的取决于实现。

于 2009-05-28T01:30:40.307 回答