Search code examples
javac++memorydynamicallocation

Dynamic allocation in java or c++


If I have a pointer in C++, let's say int* array;, I allocate memory for the array with

array=new int[10];

Then, I initialize all 10 elements of the array, with 0,1,2,3... After that, I do array=new int[15]; will the initial first 10 values still be there? I assume not, correct me if I'm wrong.

In C there is the function realloc, which has the effect described above. Is there any equivalent in C++ or java? How can I dynamically expand an array (without using Vector class, and without copying the array each time in another array with double capacity) in C++ or Java?


Solution

  • Whenever you do new int[X] where X is an integer, in both C++ and Java, you obtain a reference to a newly allocated array.

    In Java, arrays are automatically initialized so that each entry has its default value (0 for primitive data types, null for reference data types). In C++, the array is not initialized, you get garbage on it.

    If you do:

    array = new int[10];
    array[0] = 0;
    array[1] = 1;
    // etc
    array = new int[15];
    

    the second time you create an array and put a reference to it in the variable array, you simply lose the reference to your first array. Since it is a new array, it will obey the language's rules for newly allocate arrays: in Java, array will now point to an array of size 15 filled with zeroes; in C++, array will point to an array of size 15 filled with garbage.

    In Java, the lost array will be eventually garbage collected for you. In C++, you've just created a memory leak.

    Both languages forbid you to resize or, as you put, dynamically expand an array. You can create a new one, copy everything from the old one to the new one, and discard the old one. They might provide methods that make these operations for you, but you won't expand the existing array, you will simply create a new one and copy the data from the old one to the new one.

    In Java there's no realloc (but it has Arrays.copyOf, which works similarly), and in C++ (and C as well), realloc won't really extend the array; it will allocate more memory elsewhere, deallocate the memory previously allocated, and return the new pointer: you'd have to replace any existing pointers to the new address!

    Finally, for collection classes that dynamically resize themselves, they usually have an internal array and, whenever that array gets full, the class does all that resizing internally: it allocates a new one, bigger, copies the elements, and discards the old one. Since the array is completely encapsulated in the class, you don't need to worry about references to the old array as I explained above.