Destructor not deleting allocated memory

I have a class that includes a std::uint_8 pointer and the destructor should be called to delete the allocated memory. The issue I'm having is that a complier error occurs and states that the memory was not allocated, but I know I allocated it in my default constructor. Here's my default constructor:

BigInteger::BigInteger() {
  unsigned char aArray [4];
  aArray[0] = 0;
  m_number = new unsigned char[4]
  m_number = aArray;
  m_digitCount = 0;
  m_sizeReserved = 4;
}

and here's my destructor:

BigInteger::~BigInteger() {
    delete [] m_number;
}

unsigned char aArray [4] here you create an array of 4 elements on the stack. These will go out of scope once the constructor has finished.

m_number = new unsigned char[4] now you create 4 elements on the heap. You allocate the memory and you'll be in charge of cleaning it up. Not an issue, you do so in the destructor.

m_number = aArray; now you change what m_number is pointing to, effectively losing a pointer to the memory you allocated. Now you have a leak.

Any use of m_number outside of this constructor is now undefined behaviour, because you're accessing memory you no longer own.

delete [] m_number; now you're deleting memory you don't own. UB.

Don't reassign m_number and you won't have these issues. Better yet, use std::vector and watch as these manual memory management problems melt away.


That line

m_number = aArray;

assigns a local variable's address to m_number .

That address cannot be used in conjunction with delete [] m_number; , the memory address allocated with new unsigned char[4] is overridden and lost after that assignment.


You have a classical scenario of a memory leak . In essence what you are doing is the following:

  • Allocate memory ( m_number = new unsigned char[4] )
  • Override the pointer that points to that allocated memory ( m_number = aArray )
  • Never delete the allocated memory as you no longer know where it is - you have lost the pointer to it (it got overwritten)
  • 链接地址: http://www.djcxy.com/p/82816.html

    上一篇: 哪里分配了变量引用,堆栈还是堆?

    下一篇: 析构函数不删除分配的内存