0

I have a vector of wchar_t* like this:

std::vector<wchar_t*> myvector;

and a function that take a string and insert it into the vector

void myfunction(wchar_t* mystring)
{
    myvector.push_back(mystring);
}

myfunction(L"this is my string");

when I close the program I need to delete the allocated memory of the vector so that I don't have a memory leak, to do this I'm trying to do this:

for (std::vector<wchar_t*>::iterator it = myvector.begin(); it != myvector.end(); ++it)
{
    delete [] *it;
}

it compiles, all works fine but when it's time to deallocated the memory I have a rountime error:

error http://k.min.us/iklWGE.png

why? how can I fix this?

Stefano
  • 3,213
  • 9
  • 60
  • 101

4 Answers4

4

With this myfunction(L"this is my string"); you don't create a new string. It's a constant string that's stored somewhere in your exe. And since you don't explicitly new it, you don't need to delete it either.
Only use new and delete and new[] and delete[] in pairs!

Xeo
  • 129,499
  • 52
  • 291
  • 397
1

Only delete what you new. You are not using new anywhere, neither directly nor indirectly so there’s nothing to delete. As Xeo said, a better solution is to use std::wstring.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

You should not delete string literals.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
0

You haven't allocated any memory yourself. If you haven't got any new[]'s in your code you don't need any delete[]'s either.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203