1
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;
}
aah134
  • 860
  • 12
  • 25
  • Multiple inheritance is when you inherit from more than one class *for one class*. Is buffer going to be a string? Why not use `std::string`? – crashmstr Oct 17 '13 at 18:28
  • 1. There is no class named `ClassA2` in your example. If you mean `msgA2`, then yes, unless it first frees the memory allocated by `msgA` constructor. 2. Hard to tell, seeing as you haven't specified any design goals. – Igor Tandetnik Oct 17 '13 at 18:28
  • oh ok, thanks, it is a plain char array with different size depending on the message, each message could have a bunch of variables, and mini buffers. – aah134 Oct 17 '13 at 18:31

2 Answers2

2

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

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
2

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

Peter Hübel
  • 196
  • 5