Question

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?

Was it helpful?

Solution

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!

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top