1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
CuberBoy
  • 15
  • 3

1 Answers1

0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • By copying str into data using a for loop, the inital issue was fixed. I have a question about what you raised with the destructor. If I write delete [] data in the destructor I get the same error as before, yet the error does not occur in the rest of the program when I use delete[] data. Any ideas? – CuberBoy Oct 30 '22 at 22:21
  • @CuberBoy For example you created an object of the class String str(temp, 4); So the object must be destructor at the end of its scope. It means that the dynamically allocated memory must be deleted. – Vlad from Moscow Oct 30 '22 at 22:23
  • @Valid From Moscow I guess I'm confused on how to do that as delete [] data doesn't work. I've only seen destructors with print statements before hence my confusion. – CuberBoy Oct 30 '22 at 22:30