okster okster - 2 months ago 20
C++ Question

Dynamic Memory Allocation inside Class

How do i dynamically allocate memory inside a class?

To clearify my question i made up an example. I would construct an instance a of A and copy it into b. After usage a and b would be destructed and the allocated memory would be freed twice in the destructor.

So how would i handle this situation?

#include <stdlib.h>

class A {
public:
char * allocatedMemory;
A(int length) {
allocatedMemory = (char *) malloc(sizeof(char) * length);
}

~A(){
free(allocatedMemory);
}
};

int main() {
A a = A(50);
A b = a;
return 0;
}


PS: To understand the Context: I am trying to figure out by example how std::string allocates and frees memory. Only the basic allocation of course.

Answer

Hi the problem you are facing is due to shallow copy. If you wont provide the copy constuctor explicitly then the default copy constructor will be provided by compiler to inialize one object using exising object. The default copy constructor does the bit wise copying. I.e. just copy the address stored in pointer of one object to another. To avoid such double free problem, you need to do deep copy. Write your own copy constructor, inside that copy constructor explicitly allocate memory for your character pointer using new then using memcpy() copy the actual content. Hope this will help.

 #include <stdlib.h>
 class A 
 {
    public:
    char * allocatedMemory;
    int length;
    A(int length):length(length) 
    {
          // i am ignoring exception due to failure in new to keep code simple
          this->allocatedMemory = new char[length];
    }
    A(const A& obj)
    {
        this->allocatedMemory = new char[obj.length];
        memcpy(this->allocatedMemory, obj.allocatedMemory);
    }
    A& operator=(const A& obj)
    {
         if(this == obj)
            return *this;
         memcpy(this->allocatedMemory, obj.memory);
         return *this;
    }


    ~A()
   {
        if(allocatedMemory)
            delete[] allocatedMemory;
   }
};

int main() 
{
    A a = A(50);
    A b = a;
    return 0;
}
Comments