I have a small understanding problem with the heap in c++.
I have created a small class to convert a Wchar_t-Array to a Char-Array. Here is a part of my convert class:
.h
class ConvertDataType
{
private:
char *newChar;
};
.cpp
size_t i;
char *newChar = new char[wcslen(WcharArray)];
wcstombs_s(&i, newChar, strlen(newChar), WcharArray, wcslen(WcharArray));
return newChar;
In the Cpp-File I create dynamically a new Char-Array in the Heap.
How do correctly delete the variable? I read a lot of different, examples…
delete[] newChar;
In a for loop:
delete[] newChar[i];
I would do it like:
~ConvertDataType(void) //deconstructor
{
delete[] newChar;
}
Is that correct? What happens with the content in newChar[i]? I just destroy the pointer, isn’t it?
Well, I have still the problem, that a memory leak happened, if I use the class?
How could that be? I added to my deconstructor delete[] newChar;.
Your solutions is correct. When you call
delete []then the memory block refer by pointer is set as free but nothing more. Your content will still be there until you allocate another memory in this address block and you overwrite the data. But you cannot rely on reading from deleted memory. Sometimes it works but it is “an accident”.