Home > Software engineering >  Unable to delete instance variable array in C
Unable to delete instance variable array in C

Time:10-31

I am implementing a string class in C , and I have come across an issue when trying to delete the char[] that contains the data of the string:

class String
{
    public:
        String();
        String(char str[], int size);
        ~String();
        void clear();
    private:
        char *data;
        int size;
};

String::String()
{
    size = 0; 
}

String::String(char str[], int _size)
{
    data = str;
    size = _size;
}

String::~String() {}

void String::clear()
{
    if(size > 0)
        delete []data;
    size = 0;
}

int main()
{
    char temp[] = {'a','b','c','d'};
    String str(temp, 4);
    str.clear();
}

This code results in an error, VSCode simply says "Exception has occurred. Unknown signal" and the program crashes once the delete []data line is reached. The program works without this line, but I want to prevent memory leaks.

I've tried to declare a char* and assing that to new char[4], and from there populate each value one by one. This did nothing. Looking in the debugger, the correct array is assigned to data in str, so I memory does indeed seem to be allocated to the program, yet I just do not understand why I cannot delete the array. Is it const for some reason? Any thoughs?

CodePudding user response:

You are trying to apply the operator delete to this array with automatic storage duration

char temp[] = {'a','b','c','d'};

due to the constructor

String::String(char str[], int _size)
{
    data = str;
    size = _size;
}

that just copies the address of the first element of the array in the data member data.

You need to allocate dynamically an array and copy the passed array in this dynamically allocated array.

Pay attention to that the destructor deletes nothing

String::~String() {}

Also you need explicitly define at least the copy constructor and the copy assignment operator.

  • Related