我编写了一个自定义字符串和向量类。在将字符串添加到向量时偶尔(但始终如一),程序会尝试删除char指针(应该为null),从而导致seg错误。即使一步一步地通过调试器,我也无法弄清楚这个指针通常是不是一个nullptr。
这是我的三个构造函数,用于我的字符串类,以及= overload,它是发生段错误的地方。注意,我确实有一个简单的析构函数,如果它们不为null,则删除数据和tempreturn。
//default constructor
AString::AString(){
this->length = 0;
this->cap = 0;
this->data = nullptr;
this->tempReturn = nullptr;
}
//constructor with arguments for char*
AString::AString(const char* newData){
this->length = strlen(newData);
this->cap = this->length + 1;
this->data = new char[this->cap];
this->tempReturn = nullptr;
for(int i = 0; i < this->length; i ++){
this->data[i] = newData[i];
}
this->data[length] ='\0';
}
//constructor with arguments for passing a string by reference
AString::AString(const AString& newData){
this->length = newData.length;
this->cap = this->length + 1;
this->data = new char[this->cap];
this->tempReturn = nullptr;
for(int i = 0; i < this->length; i++){
this->data[i] = newData.data[i];
}
this->data[length] ='\0';
}
//called with the = string reference
AString& AString::operator= (const AString& newData){
if(data != nullptr){
delete[] data; //This is where it seg faults.
}
this->length = newData.length;
this->cap = newData.length + 1;
this->data = new char[this->cap];
for(int i = 0; i < this->length; i ++){
data[i] = newData.data[i];
}
this->data[length] ='\0';
return *this;
}
在该行,数据应为nullptr,长度应为零。但是,每次在相同的元素,数据填充的位置不包含字符,长度为33. tempreturn,也应该为null,似乎持有无意义的字符
另外作为参考,我的向量构造函数和推回方法导致了seg错误
//default constructor setting number of elements to empty, and give a
//default capacity and initialize array;
template <class T>
AVector<T>::AVector(){
this->cap = 10;
this->numElements = 0;
this->data = new T[cap];
}
template <class T>
void AVector<T>::pushBack(T type){
//add it to the end of the current index
this->data[numElements] = type; //line that leads into the segfault
//increase the tracker for how many elements added
numElements++;
//if new element exceeds previously established array
if(numElements >= cap) {
increaseCapacity(this->cap * 2);
}
}