Search code examples
c++arraysnew-operator

Creating an array using new without declaring size


This has been bugging me for quite some time. I have a pointer. I declare an array of type int.

int* data;
data = new int[5];

I believe this creates an array of int with size 5. So I'll be able to store values from data[0] to data[4].

Now I create an array the same way, but without size.

int* data;
data = new int;

I am still able to store values in data[2] or data[3]. But I created an array of size 1. How is this possible?

I understand that data is a pointer pointing to the first element of the array. Though I haven't allocated memory for the next elements, I still able to access them. How?

Thanks.


Solution

  • Normally, there is no need to allocate an array "manually" with new. It is just much more convenient and also much safer to use std::vector<int> instead. And leave the correct implementation of dynamic memory management to the authors of the standard library.

    std::vector<int> optionally provides element access with bounds checking, via the at() method.

    Example:

    #include <vector>
    int main() {
        // create resizable array of integers and resize as desired
        std::vector<int> data; 
        data.resize(5);
        // element access without bounds checking
        data[3] = 10;
        // optionally: element access with bounds checking
        // attempts to access out-of-range elements trigger runtime exception
        data.at(10) = 0; 
    }
    

    The default mode in C++ is usually to allow to shoot yourself in the foot with undefined behavior as you have seen in your case.

    For reference:


    Also, in the second case you don't allocate an array at all, but a single object. Note that you must use the matching delete operator too.

    int main() {
        // allocate and deallocate an array
        int *arr = new int[5];
        delete[] arr;
        // allocate and deallocate a single object
        int *p = new int;
        delete p;
    }
    

    For reference: