The Explanation:
Since we are dealing with C++, there is pretty much no reason to use new int[N]
instead of std::vecotr<int>
of a size N
.
To explain what is happening in your code: You create a pointer named array1
and allocate memory enough to contain N
integers. You do the same with second pointer, called array2
. Since the names array1
and array2
are just pointers to memory, what they point to can be changed. In the line array2 = array1
you change to what is pointing array2
to memory allocated and pointed to by array1
pointer.
So what happens now? Really bad stuff. You are encountering a memory leak. The memory that was pointed to by array2
is still there, still allocated, but you are unable to access it, since your only access to it (array2
pointer) now points to entirely different part of memory. You now also have 2 pointers that point to the same memory (originally the memory that was allocated in the line int *array1 = new int[N]
).
How to improve your code?
Use std::vector<int>
. Vector class comes with well written and safe assignment operator that will work for you here:
std::vector<int> array1(N);
std::vector<int> array2(N);
array2 = array1;
Now you have 2 identical vectors, memory is managed well (array1
and array2
are separate entities. They do not share the same memory and can be freely changed without affecting the other one) and your code looks pretty.
What if you cannot change everything to std::vector
?
You mentioned having an array that you pass into a function. Let's call it an original_array
of a size N
. Consider this code, which uses similar signature, but uses safe memory management by converting array to vector:
void copy_and_do_stuff(int original_array[], int N)
{
std::vector<int> array2;
std::copy(original_array, original_array + N, array2.begin());
// here, the vector "array2" is a copy of your `original_array`. Changes
// to it will not affect your argument.
// ... do whatever you need to do in this function ...
}
Remember to add #include <vector>
and #include <algorithm>
to use vectors and std::copy
function.