2026-08-21
assign.cpp
#include <algorithm>
// Buffer owns `data`, an array of `size` ints.
Buffer& Buffer::operator=(const Buffer& other) {
delete[] data;
data = new int[other.size];
std::copy(other.data, other.data + other.size, data);
size = other.size;
return *this;
}
This breaks on self-assignment (buf = buf;). Find the bug and fix it.
Answer
delete[] data frees the memory before other.data is read. When other is *this, the copy then reads from memory that was just freed. Add a self-assignment guard at the top: if (this == &other) return *this;