The task is to write your class "String". Faced such a problem: during program execution error " Expression:CrtlsValidHeapPointer(block) ".

I suppose there is an error somewhere in constructors or assignments, but I can't figure it out.

 #include <cstring> #include <iostream> class my_string { private: int length; char *symbols; public: my_string() { length = 0; symbols = new char[100]; } ~my_string() { delete symbols; } my_string(const my_string& s) { length = s.length; symbols = new char(*s.symbols); } my_string my_string::operator=(const my_string& s) { length = s.length; symbols = new char(*s.symbols); return *this; } my_string my_string::operator+=(const my_string& s) { my_string tmp; delete tmp.symbols; length = strlen(symbols) + strlen(s.symbols); tmp.symbols = new char[length + 1]; strcpy(tmp.symbols, symbols); strcat(tmp.symbols, s.symbols); delete symbols; symbols = new char[length + 1]; strcpy(symbols, tmp.symbols); delete tmp.symbols; return *this; } bool my_string::operator==(const my_string& s) { if (strcmp(symbols, s.symbols)) return false; else return true; } my_string clean_string() { delete symbols; my_string(); return *this; } }; 

I enter the data in the symbols with the help of std::cin>>symbols , but removed it so as not to litter the code

  • one
    use the debugger - Abyx

1 answer 1

  1. All cases when done

     symbols = new char(*s.symbols); 

    it's some kind of nonsense. This allocation of memory for one character of a line and copying of one character . Of course, one character is completely inadequate for storing a string of nonzero length.

    At the same time, in the implementation of the operator += such nonsense is not observed - there the memory is allocated more or less correctly. Why is there such a difference?

  2. The release of memory allocated via new[] is done via delete[] , and not via delete .

  3. In the operator += however, the mass of nonsense is written. For example, delete tmp.symbols; is done at the end delete tmp.symbols; , after which the tmp destructor will be automatically called, which again will make delete tmp.symbols; . Everything will be covered.

  4. The assignment operator must release the old contents of the object, and then copy the new into it. I do not see you releasing old content. In general, your assignment operator coincides with the copy constructor, which is pointless.

  5. What did you want to say with this?

     my_string(); 

    inside clean_string ? And why clean_string return some string by value?

  6. Another mass of minor oddities and errors.

  • Many thanks, I will correct - zhuk