使用 strcpy 时出现异常错误

Exception errors when using strcpy

本文关键字:异常 错误 strcpy 使用      更新时间:2023-10-16

我正在为类开发BST。该类中有 5 个文件,其中 2 1/2 个我无法编辑(作为 OOP 中的练习)。我无法编辑 data.h、驱动程序.cpp或 bst.cpp 的公共成员。

尝试在我的数据中使用 strcpy 时,我收到一些异常错误.cpp文件。这些是相关的,因为我在 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);
    }
}

同样,我无法编辑函数原型,因为它是公共成员。

在数据中。

char const * const getName() const { return name; }

在数据中.cpp

void Data::setName(char const * const name)
{
    strcpy(this->name, name);
}

我还尝试使用重载 = 运算符并遇到了同样的问题。调用它的代码看起来像

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

而在数据方面.cpp

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;
}

更新,以回应OP的评论

如果允许NULL Data::name,则需要进行更多检查。

Data& Data::operator=(const Data& data2)
{
   // Prevent self assignment.
   if ( this != &data2 )
   {
      if ( this->name == NULL )
      {
         if ( data2.name == NULL )
         {
            // Nothing needs to be done.
         }
         else
         {
            this->name = new char[strlen(data2.name) + 1];
            strcpy(this->name, data2.name);
         }
      }
      else 
      {
         if ( data2.name == NULL )
         {
            delete this->name;
            this->name = NULL;
         }
         else
         {
            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;
}