简体   繁体   中英

i have get error heap error using constructor ( use memory dinamic char *t = new char [10] t ="test123456";) and in distructor delete [] t; error

error heap memory, memory corruption, #181 just don't understand it. Some time try use copy ctor and it the same error. Can You explain me

Test::Test() {
    desc = new char[4];`
    desc = "Try";
} 

Test::~Test() {delete [] desc; }

It fails because you do not understand basics of C++.

desc = new char[4]; desc = "Try";

This line of code first allocates memory for 4 characters, returns the pointer to allocated memory and stores it in desc . However, the next moment you completely lose this pointer, and now assign "Try" (a string literal) to desc . Now your desc points to "Try".

Here

Test::~Test() {delete [] desc; }

you delete the pointer, which points to "Try" - as if you would do delete "Try" . But you can't delete a string literal, you did not create a it.

Hence the crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM