Array of zero size?

2020-04-18 06:31发布

问题:

Generally we declare the array in following format:

DataType array_name[SIZE];

SO If I tried creating 0 length array for e.g.

int arr[0]; //Line#1
arr[0] = 5; //Line#2

I do not get any error when above code is executed.In this case is memory allocated for single integer?

回答1:

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.



回答2:

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.



标签: c++ arrays size