2

I want to dynamically allocate an array of std::string. There is a function to allocate. I can call the function as many number of times as I want through out the program. If the pointer to the array is already allocated, I want to release the memory first then allocated the new one.

Here is what I tried:

std::string *names;
bool already_allocated = false;
void allocate( int n)
{
    if( already_allocated)
    {
        delete names;
    }
    names = new std::string[n];
    already_allocated = true;
}

int main()
{
    allocate(5);
    allocate(6);
    return 0;
}

But it is giving runtime error in the 2nd allocate() call for the line delete names

Am I misunderstanding something?

1
  • 4
    Why not use std::vector<std::string> and resize? Commented Jun 1, 2013 at 11:27

3 Answers 3

2

You have to use delete [] names; because you want to delete an array of strings, delete names; deletes a single object.

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

Comments

2

You cannot invoke delete names on an array, you should use

 delete[] names 

instead.

How about use a std::vector<std::string> for your names data sructure instead?

Comments

1

When you allocate memory using new you can use delete operator but when you allocate memory using new[] then to avoid memory leak use delete[] operator, to delete memory allocated for an array.

delete[] names

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.