Good day. Please help. Now I am studying the inheritance of C ++ classes, and wrote a small code for this case, but the program crashes at the stage of the destructor with the error "Expression: _CrtIsValidHeapPointer (block)". I am writing in Visual Studio 2015. If you do not pass an instance of class A to an instance of class B, an error does not occur.

#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; class A { protected: char *M; char *Z; public: A() { M = nullptr; Z = nullptr; } A(char *z) { Z = new char[strlen(z) + 1]; strcpy_s(Z, strlen(z) + 1, z); } char* get_Z() { return Z; } ~A() { cout << "Destruct" << endl; delete[]M; delete[]Z; } }; class B : public A { public: B() :A() { } B(A &aA) { Z = aA.get_Z(); } void show() { cout << "Z2: " << Z << endl; } }; void main() { A as("qwerty"); cout << as.get_Z() << endl; B cv(as); cv.show(); } 

    1 answer 1

    AT

     B(A &aA) { Z = aA.get_Z(); } 

    you assign a value to field Z which it has in aA ( as in main ). Then release it both in the destructor as , and in the destructor cv .

    Twice one memory can not be freed ...

    Still in the constructor

     A::A(char *z) 

    you do not assign the value of M , and it indicates do not understand where. In the destructor, you release it; don’t understand that what you can’t do either.

    • Thanks for the answer! Everything related to M I removed from the code. How can I then correctly transfer to class B the value of field Z from class A? After all, if I don’t pass an instance of class A to class B, I don’t know how to convey the value in another way. With respect! - white
    • You should not transfer the value of the pointer, but allocate a new memory and copy the string into it. - Harry
    • Do you mean to declare a dynamic buffer array in the global scope and copy a string from class A into it, and then copy from this buffer to a class B field? - white
    • You already did this: Z = new char[strlen(z) + 1]; strcpy_s(Z, strlen(z) + 1, z); Z = new char[strlen(z) + 1]; strcpy_s(Z, strlen(z) + 1, z); Do the same ... - Harry
    • That is, you propose to do so: - white