I have a small memory leak in my code regarding Strings in CLI/C++. I've tried to fix the leak by deleting my unsigned char array, but when I do, I get a Memory Access Violation.
I assume this is because the System::String is a ref type, and because of that, the memory is associated with both 'testString' and 'uch' in the code below. Is that correct? If so, how can I separate the memory so that I can free up the memory and still return a System::String?
myStatus get_testString(String^% testString)
{
uchar* uch = 0;
bool b = MgdStringToUChar(testString, uch);
myStatus s = m_NativeMsg->get_testString(uch);
testString = (reinterpret_cast<const char*>(uch));
delete []uch;//this line causes an error
uch=0;
return s;
}
static bool MgdStringToUChar(System::String^ s, uchar*& uch)
{
pin_ptr<const wchar_t> wch = PtrToStringChars( s );
int len = (( s->Length+1) * 2);
size_t * st = 0;
char *ch = new char[ len ];
bool result = wcstombs_s(st,ch, len, wch, len ) != -1;
if(!result)
throw (gcnew Exception("Could not parse string in :: MgdStringToUChar"));
uch = new uchar[len];
int i=0;
while(i<len+1)
{
uch[i] = ch[i];
i++;
}
delete st;
st=0;
delete [] ch;
ch=0;
return true;
};