Hello,
In destructor when I w
ant delete array I have heap corruption error.
If I add array = NULL; before delete[] array, this problem has been solved.
could you please more explain it?
Why I should add array = NULL; in Line 16?
The problem is in your constructor. When the object is constructed, the data members are constructed, and then the body of the constructor runs.
- There's nothing to construct length, so it gets whatever random data is in memory at that moment.
- The array member is constructed using the the uninitialized length member.
- The body of the constructor runs and you set length to length1.
I think you can fix this by changing the constructor to: K(int length1) : length)length1) {}
This will construct length() from length1. Then array will get assigned from length.
Thanks coder777 I was focusing on the destructor and not the constructor :P
@Shervan360
So what does the above code doing?
* Line 1 allocates an int with a dynamic lifetime ("on the heap").
* Line 2 then makes the pointer to that dynamic memory now point to nothing (nullptr). The original memory still exists and has not been cleaned up. This is now a memory leak, because you have no way of accessing or deleting the memory you created on Line 1.
* Line 3 is calling delete on a nullptr (same thing as NULL), and is a no-op.
In other languages like C# and Java, we have Garbage Collector.
In C and C++ we don't have garbage collector and is better we don't use destructor manually. Are our programs in C++ are optimal(has good performance)?
Because of all memory allocation in C++ without a garbage collector deleted after the end of the program.