【发布时间】:2014-06-08 22:57:44
【问题描述】:
通过阅读其他 stackoverflow 问题,我知道此错误意味着我正在尝试取消引用空指针。但是,我无法弄清楚我的代码在哪里取消引用空指针。我正在尝试将 char* (cstring) 设置为非空值,但出现访问冲突错误。代码如下:
void Data::setName(char const * const name)
{
if (this->name)
delete[] this->name;
this->name = new char[strlen(name) + 1]; // This is where my code breaks in debug mode
strcpy(this->name, name);
}
name 是一个 char* 变量,它被初始化为 null。重载的赋值运算符正在调用 setName:
Data& Data::operator=(const Data& data2)
{
//if it is a self copy, don't do anything
if (this == &data2)
return *this;
else
{
setName(data2.name); // Here is the call to setName
return *this;
}
}
附:看在上帝的份上,请不要告诉我我不应该使用 cstrings!我知道 std::string 更好,但这是针对需要 cstrings 的家庭作业。
【问题讨论】:
-
请发布您的整个课程,以及您用于测试的 main() 程序。否则,我们只有两个没有逻辑错误(但有其他问题)的函数。
-
另外:
if (this->name)这不是必须的。调用delete[]时无需检查nullptr 或NULL。另外,如果我将一个空指针传递给setName会怎样?你的程序会有未定义的行为,因为 strlen(0) 是 UB。 -
"另外,如果我将空指针传递给 setName 会怎样?"这正是我的问题所在!
-
好的。但是如果传递了一个空指针怎么办?您可以忽略它并让程序可能崩溃(这就是 std::string 所做的)。
-
"看在上帝的份上,请不要告诉我我不应该使用 cstrings!" -- 我认为你应该去你的教授办公室,告诉他/她,除非任务是实现
std::string,否则你将使用std::string。记住要始终保持眼神交流。
标签: c++ access-violation cstring