初始化固定大小的字符数组时没有足够的空间用于空终止符时没有编译器错误 [英] No compiler error when fixed size char array is initialized without enough room for null terminator

查看:51
本文介绍了初始化固定大小的字符数组时没有足够的空间用于空终止符时没有编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 c 个字符数组:

Suppose I have the following c char arrays:

char okaysize4[5] = "four";   // line 5
char toosmall4[4] = "four";   // line 6
char toosmall3[3] = "four";   // line 7

当我用 gcc 4.4.7 编译时,出现以下错误:

When I compile with gcc 4.4.7, I get the following error:

array.c:7: 警告:字符数组的初始化字符串太长

array.c:7: warning: initializer-string for array of chars is too long

第 7 行预计会出现此错误,因为我试图将 5 个字符 ("four" + \0) 填充到 3 元素数组中.由于 5 元素数组足够大,第 5 行也不会出现错误.

This error is expected for line 7, as I am trying to stuff 5 chars ("four" + \0) into a 3 element array. Also no error is expected for line 5 as the 5 element array is big enough.

然而我很惊讶第 6 行没有类似的错误.最终在 toosmall4 中初始化的是一个未终止的字符串,它会导致各种麻烦.

However I'm surprised there is no similar error for line 6. What ends up getting initialized in toosmall4 is an unterminated string, which can cause all sorts of trouble.

我的理解是 c 字符串文字 "four" 应该是五个字符长,因为有空终止符.实际上sizeof("four")是5,那么为什么编译器在这里不报错呢?

My understanding is that the c string literal "four" should be five characters long, due to the null terminator. In fact sizeof("four") is 5. So why does the compiler not give an error here?

有什么方法可以改变我的声明/定义/初始化,以便在这种情况下标记错误?

Is there some way I can alter my declaration/definition/initialization so that an error is flagged in this case?

推荐答案

这是第 6 行的预期行为,来自 draft C99 标准 部分 6.7.8 Initialization14 说(强调我的):

This is expected behavior for line 6, from the draft C99 standard section 6.7.8 Initialization paragraph 14 says (emphasis mine):

字符类型的数组可以用字符串初始化文字,可选地括在大括号中.的连续字符字符串文字(包括终止空字符如果有空间或数组大小未知) 初始化数组的元素.

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

在 C11 草案标准中,具有类似措辞的相关部分是 6.7.914,并且作为 C 常见问题解答:

In the C11 draft standard the relevant section with similar wording is 6.7.9 paragraph 14, and as the C FAQ says:

因此数组不是真正的 C 字符串,不能与strcpy、printf的%s格式等

The array is therefore not a true C string and cannot be used with strcpy, printf's %s format, etc.

正如 Keith Thompson 指出的那样,C++ 更严格,C++ 标准草案中的相关部分说明如下:

As Keith Thompson noted, C++ is stricter, the relevant section in the draft C++ standard says the following:

初始化器的数量不应多于数组元素.[示例:

There shall not be more initializers than there are array elements. [ Example:

char cv[4] = "asdf"; // error

格式错误,因为隐含的尾随 '\0' 没有空间.—结束示例]

is ill-formed since there is no space for the implied trailing ’\0’. —end example ]

这篇关于初始化固定大小的字符数组时没有足够的空间用于空终止符时没有编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆