1

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...

1
  • 2
    I am obliged to mention std::vector. Are you aware of it? Commented Mar 23, 2012 at 21:54

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Beware of exception safety, its better to use scoped/smart pointer
An even better way is to use std::vector.
assuming that you need fix sized array, use array Class(TR1) on windows.
@C-x C-t positive it will fit on the stack?
2

Yes it will, unless you are deleting the memory allocated everytime by

temp = new string [high + 1];

in your "rest of the code".

Comments

1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.