使用 strcpy 时出现异常错误
Exception errors when using strcpy
我正在为类开发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;
}
相关文章:
- VisualC++ 2010 有没有办法找出有关未处理异常错误的更多详细信息
- 打开CV异常错误,尽管我的代码是正确的
- 异常错误C++ //Visual Studio
- 提升序列化异常错误
- 返回内存异常错误的矢量
- 使用用户定义的函数查找完美数时出现浮点异常错误
- cv::内存位置出现异常错误
- OpenCV未经处理的异常错误
- 分数简化算法,浮点异常错误
- 为什么我会收到浮点异常错误
- 文本框为空时,C++Windows窗体应用程序出现未处理的异常错误
- 文本框为空时C++ Windows 窗体应用程序未处理的异常错误
- 函数传递映射时出现异常错误
- 在MS Visual Studio 2010上使用带有Cuda互操作的OpenGL缓冲区时出现异常错误
- 未处理的异常错误
- C++:关闭控制台应用后出现异常错误
- 写入对象时运行时引发异常错误
- C++ C# 包装器空异常错误
- Coin3D(Open Inventor)中出现未处理的异常错误
- Stack Pop()函数出现未处理的异常错误