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

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

问题描述

假设我有下面的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个字符(四有+ \\ 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字符串四有应该是5个字符,由于空终止符。事实上的sizeof(四大) 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号线的行为,从的草案C99标准部分 6.7.8 初始化的段落的 14 的说(的重点煤矿的):

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.9 段的 14 的,并作为的ç常见问题解答说

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.

由于基思·汤普森指出, 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天全站免登陆