我有一个错误
12 SIZE: 3 CAPACITY: 4
12 SIZE: 4 CAPACITY: 4
DESTRUCTOR
proj1(53055,0x10121c580) malloc: *** error for object 0x600001ac1110: pointer being freed was not allocated
proj1(53055,0x10121c580) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort /Users/mascai/root_folder/dev/projects/03_cpp_examples/02_ide/build/proj1
我的代码:
template<class T>
class Vector {
public:
Vector() = default;
Vector(size_t size) : size_(size), capacity_(size * 2) {
data_= new T[capacity_];
}
Vector(size_t size, const T val) : size_(size), capacity_(size * 2) {
data_= new T[capacity_];
for (size_t i = 0; i < size_; ++i) {
data_[i] = val;
}
}
Vector(const Vector& other) {
data_ = other.data_;
size_ = other.size_;
capacity_ = other.capacity_;
}
const Vector& operator=(const Vector<T>& other) {
data_ = other.data_;
size_ = other.size_;
capacity_ = other.capacity_;
return *this;
}
~Vector() {
cout << "DESTRUCTOR" << endl;
if (data_) {
delete[] data_;
}
size_ = 0;
capacity_ = 0;
}
T operator[](size_t idx) const {
if (idx < size_) {
return *(data_ + idx);
}
throw std::invalid_argument("Inde out of range");
}
void push_back(const T& val) {
size_ += 1;
if (size_ > capacity_) {
capacity_ *= 2;
T* new_data = new T[capacity_];
for (int i = 0; i < size_ - 1; ++i) {
*new_data++ = *data_++;
}
delete[] data_;
data_ = new_data;
} else {
*(data_ + size_ - 1) = val;
}
}
size_t size() const {
return size_;
}
size_t capacity() const {
return capacity_;
}
private:
T* data_ = nullptr;
size_t size_ = 0;
size_t capacity_ = 0;
};
int main() {
Vector<int> v(2, 111);
assert(v[0] == 111);
v.push_back(12);
cout << v[2] << " SIZE: " << v.size() << " CAPACITY: " << v.capacity() << endl;
v.push_back(12);
cout << v[3] << " SIZE: " << v.size() << " CAPACITY: " << v.capacity() << endl;
v.push_back(13);
}
看起来问题与删除的无效使用有关。我应该解决什么问题?
当您添加新元素并需要分配更多内存时,您会遇到以下不幸的序列:
for (size_t i = 0; i < size_ - 1; ++i) {
*new_data++ = *data_++;
}
delete[] data_;
当您之后
delete[] data_
时,它不保存原始地址,因此您的程序具有未定义的行为。
我现在还推荐
delete
你的复制构造函数和复制赋值运算符。它们不起作用。