aah134
aah134

Reputation: 860

inheritance memory management managing

class base
{
public:
   base() : buffer(NULL) {}
private:
   unsigned char * buffer;
};

class msgA : public base
{
public:
   msgA() 
   {
       //alocate memory for buffer size X
       this->buffer = new (std::nothrow) unsigned char[A_MSG_SIZE]; // A_MSG_SIZE = 20
   }
};

class msgA2 : public msgA
{
   msgA2() 
   {
       //alocate memory for buffer size X2
       this->buffer = new (std::nothrow) unsigned char[A2_MSG_SIZE]; // A2_MSG_SIZE = 30
   }
};
  1. is there a memory leak in msgA2 constructor?
  2. whats the best way to design this without causing any issue?

should I delete buffer then allocate a new one in class msgA2 because msgA constructor were called previously

edit: there is a destructor delete []

I added the following to the constructors

if(this->buffer != NULL)
{
    delete [] this->buffer ;
    this->pMsgBuffer = NULL;
}

Upvotes: 1

Views: 143

Answers (2)

Peter Hübel
Peter Hübel

Reputation: 196

You could let base allocate the memory, passing the buffer size as arguments for the constructors. Something like

class base
{
protected:
   base(size_t size) { /* allocate */ }
   unsigned char * buffer;
};

class msgA : public base
{
public:
   msgA() : base(X)
   {
   }
protected:
   msgA(size_t size) : base(size) 
   {
   }
};

class msgA2 : public msgA
{
public:
   msgA2() : msgA(X2)
   {
   }
};

This way you could have base manage the memory (and delete the buffer in the destructor).

Upvotes: 2

LihO
LihO

Reputation: 42083

"is there a memory leak in ClassA2 constructor?"

Currently as your code stands, there's no memory allocation and therefore no memory leak. Yet I worry about the way you are going to allocate the memory for you buffer member. Will it be in constructor? Will there be a need for a destructor that will be explicitly taking care of this memory? If you have to implement destructor, don't forget about copy constructor and assignment operator (Rule of Three).

"whats the best way to design this without causing any issue?"

The best is to avoid handling memory management on your own. Use std::vector<unsigned char> for binary data or std::string if it is a string.

Upvotes: 2

Related Questions