本文介绍了为什么编译器没有检测到字符串常量初始化中的越界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我在一本书中读到了这个问题及其答案.但我不明白这本书的理由.

I read this question and its answer in a book. But I didn't understand the book's justification.

下面的代码会编译吗?

int main()
{
   char str[5] = "fast enough";
   return 0;
}

答案是:

是的.编译器永远不会检测到如果数组的边界是错误的超过.

我无法理解.

有人可以解释一下吗?

推荐答案

在 C++ 标准中,8.5.2/2 Character arrays 说:

In the C++ standard, 8.5.2/2 Character arrays says:

初始化器的数量不应多于数组元素.

在 C99 标准中,6.7.8/2 Initialization 说:

In the C99 standard, 6.7.8/2 Initialization says:

任何初始化程序都不应尝试为未包含在实体中的对象提供值正在初始化

C90 6.5.7 Initializers 表示类似.

C90 6.5.7 Initializers says similar.

但是,请注意,对于 C(C90 和 C99),'\0' 终止字符将被放入数组中如果有空间.如果终止符不适合,这不是错误(C99 6.7.8/14:字符串文字的连续字符(包括终止空字符,如果有空间或数组大小未知)初始化大批").

However, note that for C (both C90 and C99) the '\0' terminating character will be put in the array if there is room. It's not an error if the terminator will not fit (C99 6.7.8/14: "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").

另一方面,C++ 标准有一个示例,表明如果终止字符没有空间,则应诊断错误.

On the other hand, the C++ standard has an example that indicates an error should be diagnosed if there's not room for the terminating character.

在任何一种情况下,这都应该在所有编译器中被诊断为错误:

in either case, this should be diagnosed as an error in all compilers:

char str[5] = "fast enough";

也许 ANSI 之前的编译器没有那么严格,但任何合理的现代编译器都应该对此进行诊断.

Maybe pre-ANSI compilers weren't so strict, but any reasonably modern compiler should diagnose this.

这篇关于为什么编译器没有检测到字符串常量初始化中的越界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:19