Reputation: 318
Does the following code will increase the allocated memory continuously as it is called repeatedly?
void ArrayStorage::merge(int low, int mid, int high)
{
int start = low;
int marker = low;
int secondStart = mid + 1;
temp = new string [high + 1];
//rest of the code
}
please share with me if you know about it...
Upvotes: 1
Views: 139
Reputation: 258548
Yes, because you're not deleting the memory allocated by new
.
The correct way is:
void ArrayStorage::merge(int low, int mid, int high)
{
int start = low;
int marker = low;
int secondStart = mid + 1;
temp = new string [high + 1];
//rest of the code
delete[] temp; //free the memory
}
In C++, there's no automatic memory management for dynamically allocated objects. Everytime you call new
or malloc
(this method is usually for C), you allocate memory in dynamic storage, which you are responsible for freeing, via delete
or free
respectively. In your case, you allocate an array of size high + 1
which you need to free via delete[]
.
EDIT: As others have pointed out, maybe std::vector
is better suited, but it depends on what you want to do. Look it up.
Upvotes: 3
Reputation: 1591
When you call new you allocate memory off the heap. This memory is freed in one of two ways; the first way is someone calls delete on it (mainly you or a library you are using), and two is by terminating the program.
Just a pedantic note, it will eventually stop consuming memory, because your system will stop allowing new to work (there is an upper limit).
Upvotes: 1
Reputation: 11721
Yes it will, unless you are deleting the memory allocated everytime by
temp = new string [high + 1];
in your "rest of the code".
Upvotes: 2