错误:修改了X处的堆块

时间:2015-01-21 17:22:22

标签: c++ c++11 runtime-error destructor

我试图将析构函数用于结构体。但是,编译器报告了Heap block at 006651F8 modified at 00665229 past requested size of 29 gift1.exe has triggered a breakpoint.

的错误
    #include "stdafx.h"

    struct Node{
        char *name;
        int age;

        Node(char *n = 0, int a = 0){
            this->name = _strdup(n);
            age = a;
        }

        ~Node(){
            if (this->name != 0)
                delete[] this->name;
        }
    };

    int _tmain(int argc, _TCHAR* argv[])
    {

        Node node1("Andy", 20);
        return 0;
    }

我可以知道哪里出了问题吗?

如果我使用name代替this->name吗?

添加组件:

即使我按照以下答案的建议将其更改为free(this->name);,也会出现相同的错误。 Heap block at 00EA68D8 modified at 00EA6909 past requested size of 29 gift1.exe has triggered a breakpoint.

2 个答案:

答案 0 :(得分:3)

_strdup在内部使用malloc()

  

_strdup函数调用malloc 为strSource副本分配存储空间,然后将strSource复制到分配的空间。

但您使用delete[]取消分配:

  

释放先前由匹配运算符new分配的存储...如果未从相应的标准库分配函数获取传递给标准库释放函数的指针,则行为未定义。

要解决此问题,请使用std::string代替char*(或者如果您确实无法使用std::string使用free(),请阻止复制或实施Node的复制)。

答案 1 :(得分:0)

如果您检查the documentation for _strdup (aka strdup),您会看到它在内部使用malloc来分配字符串,因此必须通过调用free而不是delete来释放内存