1

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?

Forever Learner
  • 1,315
  • 2
  • 12
  • 28

2 Answers2

7

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.

Alok Save
  • 190,255
  • 43
  • 403
  • 518
  • Thanks Als , that makes sense. – Forever Learner Apr 27 '12 at 15:22
  • 1
    "probably some compiler extension allows this to compile": It might have something to do with flexible array members. gcc supported them with `[0]` size before C99 gave the syntax without size. May have leaked into its C++ behaviour. – Daniel Fischer Apr 27 '12 at 15:31
  • @Als: Thanks. I tried the flag from command line and it gave me the helpful warning. `g++ -pedantic array_size.cpp array_size.cpp: In function ‘int main()’: array_size.cpp:10:11: warning: ISO C++ forbids zero-size array ‘arr’ [-pedantic]` – Forever Learner Apr 27 '12 at 15:36
  • @CppLearner: Good, that confirms what I said in my answer :) – Alok Save Apr 27 '12 at 15:41
4

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.

shf301
  • 30,022
  • 2
  • 46
  • 83