Array of zero size?

时光毁灭记忆、已成空白 提交于 2019-12-02 03:43:12

Why does the Line#1 not generate any compilation error?
Ideally, it should!
It is not legal code to create an array of size 0 on local storage.
Ideally, the compiler should issue you an error, probably some compiler extension allows this to compile but as per the standard this is not a valid code.Try compiling with -pedantic.

Reference:

C++03 Standard 8.3.4/1:

If the _constant-expression+ (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.

Further,
Why does the Line#2 not generate any compilation error?
Because writing beyond the bounds of an allocated array is Undefined Behavior. An Undefined Behavior does not need the compiler to provide you any diagnostic. Note that once the code exhibits an Undefined Behavior literally anything can happen and all bets are off.

You don't get any error because C/C++ doesn't do any range checking on arrays. arr[10000000] wouldn't give you can compile error either.

What happens is you are writing to some memory some where on the stack that isn't part of arr and who knows what will happen. It could result in an access violate and crash or randomly corrupt some other data structure.

That's a buffer overflow.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!