[英]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.错误堆内存,内存损坏,#181 就是不明白。 Some time try use copy ctor and it the same error.
有一段时间尝试使用 copy ctor 并且它出现相同的错误。 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++.它失败是因为您不了解 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
.这行代码首先为 4 个字符分配内存,返回指向已分配内存的指针并将其存储在
desc
。 However, the next moment you completely lose this pointer, and now assign "Try" (a string literal) to desc
.然而,下一刻你完全失去了这个指针,现在将“Try”(一个字符串文字)分配给
desc
。 Now your desc
points to "Try".现在您的
desc
指向“尝试”。
Here这里
Test::~Test() {delete [] desc; }
you delete the pointer, which points to "Try" - as if you would do delete "Try"
.您删除指向 "Try" 的指针 - 就像您会
delete "Try"
。 But you can't delete a string literal, you did not create a it.但是您不能删除字符串文字,因为您没有创建它。
Hence the crash.因此崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.