C++ 使用strcpy时出现异常错误

C++ 使用strcpy时出现异常错误,c++,exception,operator-overloading,strcpy,C++,Exception,Operator Overloading,Strcpy,我正在为班级准备一个BST。类中有5个文件,其中2 1/2我无法编辑(作为OOP中的练习)。我无法编辑data.h、driver.cpp或bst.cpp的公共成员 尝试在data.cpp文件中使用strcpy时,我遇到一些异常错误。这些都是相关的,因为bst.cpp中的插入函数是作为驱动程序的参数发送的数据对象 错误的形式是 Unhandled exception at 0x0F3840D9 (msvcr120d.dll) in asgmt04.exe: 0xC0000005: Access

我正在为班级准备一个BST。类中有5个文件,其中2 1/2我无法编辑(作为OOP中的练习)。我无法编辑data.h、driver.cpp或bst.cpp的公共成员

尝试在data.cpp文件中使用strcpy时,我遇到一些异常错误。这些都是相关的,因为bst.cpp中的插入函数是作为驱动程序的参数发送的数据对象

错误的形式是

Unhandled exception at 0x0F3840D9 (msvcr120d.dll) in asgmt04.exe: 0xC0000005: 
Access violation writing location 0x00000000.
这里有一些代码

在bst.cpp中

void BST::insert(const Data& data)
{
    if (index > capacity)
        grow();

    if (items[index].isEmpty == true)
    {
        items[index].data.setName(data.getName());
        nItems++;
        items[index].isEmpty = false;
        items[index].loc = index;
    }
    else if (data < items[index].data)
    {
        index = (2 * index) + 1;
        insert(data);
    }
    else
    {
        index = (2 * index) + 2;
        insert(data);
    }
}
在data.cpp中

void Data::setName(char const * const name)
{
    strcpy(this->name, name);
}
Data& Data::operator=(const Data& data2)
{
    strcpy(this->name, data2.name);
    return *this;
}
我还尝试使用重载=运算符,但遇到了相同的问题。调用它的代码看起来像

items[index].data = data; //second arg is the one passed into insert function
和在data.cpp中

void Data::setName(char const * const name)
{
    strcpy(this->name, name);
}
Data& Data::operator=(const Data& data2)
{
    strcpy(this->name, data2.name);
    return *this;
}

我怀疑在你执行命令的时候

strcpy(this->name, data2.name);
this->name
中没有足够的空间容纳
data2.name
。这里有一个建议:

Data& Data::operator=(const Data& data2)
{
    // Prevent self assignment.
    if ( this != &data2 )
    {
       if (strlen(this->name) < strlen(data2.name) )
       {
          // Assuming that you used new to allocate memory.
          delete [] this->name;
          this->name = new char[strlen(data2.name) + 1];
       }
       strcpy(this->name, data2.name);
    }
    return *this;
}

这会在
if(strlen(This->name)
行中导致另一个未处理的异常,我认为这是因为
This->name
在该点为空,您正在取消引用空指针。理想情况下,您可以通过在调试器中运行来获取正在发生的行号。可能是您的this指针或this->name指针。添加要检查的断言。@kec这似乎是问题所在。不幸的是,数据对象的默认构造函数(我不能更改)将name初始化为NULL,并且在程序运行时动态初始化它们的整个数组。