-2

I am getting some sort of memory leak with this code. Although is doesnt actually throw any error, when run through Memcheck, it detects a memory leak.

Am I supposed to also delete[] the temporary array or something?

Here is the function it is happening in:

Bob
  • 1
  • 2
  • 1
    The code is missing from your question. – Pibben Oct 11 '19 at 06:48
  • When you [edit] your question to add the code, you should also show us what kind of debugging you've done. I expect you to have run your [mcve] within Valgrind or a similar checker, and to have investigated with a debugger such as GDB, for example. Ensure you've enabled a full set of compiler warnings, too. What did the tools tell you, and what information are they missing? And read Eric Lippert's [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Toby Speight Oct 11 '19 at 12:36

1 Answers1

1

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.)

JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • yes, i forgot to mention that since this is for an assignment, we are not permitted to use std::vector and such. how would i deallocate newBinaryNum since i need that value until it is returned? – Bob Oct 11 '19 at 04:00
  • @Bob Don't deallocate it. Don't allocate it. Just declare it as a local object and let the compiler handle the details. – JaMiT Oct 11 '19 at 04:03