Every memory allocation needs to be paired to exactly one deallocation. When this function ends, the memory pointed to by newBinaryNum
has not been deallocated, and the address of that memory is not retained anywhere. Hence, memory leak.
Since you don't use any benefits of dynamic allocation for this BinaryNum
object, don't use dynamic allocation. Just declare your variable as BinaryNum newBinaryNum;
. Not only will the compiler handle the memory needs of this object, but also your code would be able to benefit from return value optimization.
(Also, you should lean on the standard library a bit more. Your manipulations of binaryAry
mimic the functionality of std::vector
. Why re-invent the wheel? Your focus in this function should be on the BinaryNum
class, so delegate the memory management details to the standard library.)