Reputation: 882
I have a dynamic array of CString
in my class, I used new
operator in constructor of my class to create that, so I wrote one line in destructor to free the memory. It doesn't cause any error but it leads to a breakpoint in runtime!
Error is :
Windows has triggered a breakpoint in Genetic Algorithm.exe.
This may be due to a corruption of the heap, which indicates a bug in Genetic Algorithm.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while Genetic Algorithm.exe has focus.
The output window may have more diagnostic information.
and the code is:
//in constructor
StringFormat = new CString[Info.VariablesCount + 1];
for (int i=0;i<=Info.VariablesCount;i++)
StringFormat[i] = "%2.3f";`
// in destructor
free(StringFormat);
Notice that StringFormat*
is a private member of class, I have some other dynamic arrays in this class too, but I can free them easily with free method, this problem is just with CString
dynamic arrays, so what am I missing?
Upvotes: 0
Views: 2291
Reputation: 18411
You have used new
operator to allocate memory, and attempting to release the memory using free
. Both have different heaps, other than some semantics they differ. You allocate using new
, release memory using delete
. Similarly, you allocate using malloc
and release the same using free
. You cannot mix them!
Also, as mentioned by others, if you use array-mode new
(and not scaler new
), you must delete it using array-mode delete
and not scalar delete
(i.e. delete[]
, and not delete
).
It is very much recommended that you use vector
, list
, CArray
, CStringArray
or some other container to have array-of-strings, rather than managing it yourself.
Upvotes: 1
Reputation: 6040
You used new[]
to allocate the CString
array. You have to use delete[]
to free it - Basic C++ memory rules.
In your destructor use: delete[] StringFormat;
Upvotes: 2