-6

What is the difference between int* arr = new int [5]; and int* arr = new int();?

  • 5
    Be aware of [**Undefined Behaviour**](https://en.wikipedia.org/wiki/Undefined_behavior) - the first *appears* to work for 5 `int`s, but it is actually completely illegal. You are just overwriting some random memory that happens to sit next to the single `int` that you created. If you need 5 `int`s, make sure you allocate space for all of them. – BoBTFish May 24 '18 at 15:09
  • allocate array, and allocate a single object. I.e. `int *i = (int*)malloc(sizeof(int))` and `int* iarr = (int*)calloc(100,sizeof(int))` in C. Please read some C++ book, like The C++ Programming Language by Bjarne Stroustrup – Victor Gubin May 24 '18 at 15:12
  • This is pretty standard in C++. Have you looked at some simple use cases of the `new` operator, like [here](http://www.cplusplus.com/doc/tutorial/dynamic/)? – kedarps May 24 '18 at 15:13
  • Consider `std::vector` for practical purposes. – SergeyA May 24 '18 at 15:24

1 Answers1

2
int* arr = new int [5];

The above allocates an array of 5 int without initialising them, and assigns it to the new variable arr. The array should be freed using delete [] arr;.

int* arr = new int();

The above allocates a single value-initialized int, and assigns it to the mis-named new variable arr. The memory should be freed using delete arr;.

Accessing out-of-bounds, or trying to free something the wrong way all causes Undefined Behavior, which means neither compiler nor runtime are under any requirements whatsoever.

As your program ends shortly thereafter, it's acceptable to leak those allocations to avoid the make-work. You should add a comment that you do so intentionally though.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118