简体   繁体   English

我使用构造函数(使用 memory dinamic char *t = new char [10] t ="test123456";)并在析构函数中删除 [] t; 错误

[英]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.

相关问题 uint8_t 和无符号字符链接错误 - uint8_t and unsigned char linking error 错误:无法将char转换为wchat_t * - Error : Cannot convert char to wchat_t* 分配字符串时,char * new和delete []错误 - char* new and delete [] error when a string is assigned C ++无法删除char *,不断破坏堆 - C++ can't delete char*, keeps corrupting heap 构造函数不接受字符 * - Constructor doesn't accept char * 一个const字符串构造函数,不分配任何char内存? - A const string constructor that doesn't allocate any char memory? 为什么我收到此错误消息:“未定义引用`PerformChat(char *,char *,char *,char *,char *)&#39;” - Why do I get this error message: “undefined reference to `PerformChat(char*, char*, char*, char*, char*)'” 得到错误&#39;char16_t和char32_t未声明&#39; - Getting error 'char16_t and char32_t undeclared' “所属类别 <char> (char *)&#39;未定义但在C ++ 11之前工作; 什么改变了,我该如何修复错误? - 'TypeInfo<char>(char *)' isn't defined but worked pre-C++11; what changed, and how can I fix the error? 错误:无法将参数1的const字符串转换为const char *到size_t strlen(const char *) - error: cannot convert const string to const char* for argument 1 to size_t strlen(const char*)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM