Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c - Why doesn't the compiler detect out-of-bounds in string constant initialization?

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

Will the following code compile?

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

And the answer was:

Yes.The compiler never detects the error if bounds of an array are exceeded.

I couldn't get it.

Can anybody please explain this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

In the C99 standard, 6.7.8/2 Initialization says:

No initializer shall attempt to provide a value for an object not contained within the entity being initialized

C90 6.5.7 Initializers says similar.

However, note that for C (both C90 and C99) the '' 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").

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";

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...