潜在的问题与C标准malloc'ing字符 [英] Potential problem with C standard malloc'ing chars
问题描述
在回答了评论我的另一个答案<一个href=\"http://stackoverflow.com/questions/1247964/how-do-you-know-how-much-space-to-allocate-with-malloc/1247977#1247977\">here,我发现我的想法的可能的是C标准的孔(C1X,我没有检查与先前的,是的,我知道这是令人难以置信的可能性不大,我独自各个星球的居民中已经发现了在标准的bug)。信息如下:
When answering a comment to another answer of mine here, I found what I think may be a hole in the C standard (c1x, I haven't checked the earlier ones and yes, I know it's incredibly unlikely that I alone among all the planet's inhabitants have found a bug in the standard). Information follows:
- 6.5.3.4节(sizeof操作符)第2条规定
sizeof操作符得到其操作数的大小(以字节为单位)
。 - 该节第3段规定:
当应用于具有char类型,unsigned char型,或符号的字符,(或其合格的版本)的结果为1的操作数
。 - 第7.20.3.3描述
的void * malloc的(为size_t SZ)
,但所有这说的是malloc函数为对象,其大小分配空间由size指定,其值是不确定的
。它并没有提及在使用所有什么单位的说法。 - 附件E startes 8是的最小的为
CHAR_BIT
值,使字符的长度可以是多个字节。
- Section 6.5.3.4 ("The sizeof operator") para 2 states
"The sizeof operator yields the size (in bytes) of its operand"
. - Para 3 of that section states:
"When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1"
. - Section 7.20.3.3 describes
void *malloc(size_t sz)
but all it says is"The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate"
. It makes no mention at all what units are used for the argument. - Annex E startes the 8 is the minimum value for
CHAR_BIT
so chars can be more than one byte in length.
我的问题很简单:
在其中char是16位宽,环境将的malloc(10 * sizeof的(字符))
拨款1000个字符(20字节)或10个字节?上述第1点似乎表明前者,点2表示后者。
In an environment where a char is 16 bits wide, will malloc(10 * sizeof(char))
allocate 10 chars (20 bytes) or 10 bytes? Point 1 above seems to indicate the former, point 2 indicates the latter.
任何人有更多的C-标准福比我有这样一个答案?
Anyone with more C-standard-fu than me have an answer for this?
推荐答案
在16位字符
环境的malloc(10 * sizeof的(CHAR ))
将拨出10 字符
S(10字节),因为如果字符
16位,则该架构/实现定义一个字节为16位。 A 字符
不是一个八位位组,这是一个字节。在旧的计算机上这可能会比8位的事实上的的标准,我们有今天。
In a 16-bit char
environment malloc(10 * sizeof(char))
will allocate 10 char
s (10 bytes), because if char
is 16 bits, then that architecture/implementation defines a byte as 16 bits. A char
isn't an octet, it's a byte. On older computers this can be larger than the 8 bit de-facto standard we have today.
从C标准的有关部分如下:
The relevant section from the C standard follows:
3.6术语,定义和符号
3.6 Terms, definitions and symbols
字节 - 数据存储足以容纳基本字符集执行环境的...
byte - addressable unit of data storage large enough to hold any member of the basic character set of the execution environment...
注2 - 一个字节由比特的连续序列的,其数量是实现定义
NOTE 2 - A byte is composed of a contiguous sequence of bits, the number of which is implementation-defined.
这篇关于潜在的问题与C标准malloc'ing字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!