在测试头文件中的代码时,我遇到了各种内存错误。请让我知道同样的错误,帮助我。谢谢!
有问题的代码是下面代码块中的代码。它有评论所以它非常自我解释。
非常感谢你的帮助!!!
#include <algorithm>
class sorted_sc_array {
public:
sorted_sc_array() : size_(0), ptr_(nullptr), arr_len(1000) {
ptr_ = new signed char[arr_len];
}
~sorted_sc_array() { delete[] ptr_; }
// IMPLEMENT ME (DONE!!!! SOME EDITS REQD)
sorted_sc_array(const sorted_sc_array& A) {this->size_ = A.size_; this->ptr_ = A.ptr_; /* change this to match the definition of operator=() function */}
// IMPLEMENT ME (DONE!!!!)
sorted_sc_array& operator=(const sorted_sc_array& A) {
if (this == &A) return *this;
delete[] ptr_;
size_ = A.size_;
if (size_ == 0) ptr_ = nullptr;
else {
ptr_ = new signed char[size_];
std::copy(A.ptr_, A.ptr_ + size_, ptr_);
}
return *this;
}
// RETURNS SIZE OF THE ARRAY (i.e. HOW MANY ELEMENTS IT STORES)
int size() const { return size_; }
// RETURNS RAW POINTER TO THE ACTUAL DATA, CAN BE INVOKED AT ANY TIME
const signed char* data() const { return ptr_; }
// IMPLEMENT ME: AFTER INSERT COMPLETES THE ARRAY MUST BE IN ASCENDING ORDER (TBD!!!)
void insert(signed char c) {
if (size_ < arr_len) {
ptr_[size_++] = c;
std::sort(ptr_, ptr_ + size_);
}
else {
int arr_len_new = arr_len*2;
ptr_ = new signed char[arr_len_new];
std::copy(ptr_, ptr_ + size_, ptr_);
ptr_[size_++] = c;
std::sort(ptr_, ptr_ + size_);
}
// maybe use std::sort (myvector.begin(), myvector.end());
// if inefficient, use binary insertion
}
private:
int size_; // size of the array
signed char* ptr_; // pointer to the array
unsigned int arr_len; // dynamic mem alloc for array
}; // class sorted_sc_array
答案 0 :(得分:0)
您没有具体说明您遇到的具体错误。虽然,您的问题很可能来自忽略arr_len
成员。您可以复制size_
并正确分配内存,但在初始化或复制时忽略arr_len
。当您访问并比较未初始化的arr_len
时,这会产生问题。
答案 1 :(得分:0)
insert()
函数在增长数组时会出现许多错误。
arr_len
。ptr_
,然后将数组复制到自身。您需要使用临时变量。这解决了这些问题:
void insert(signed char c) {
if (size_ < arr_len) {
ptr_[size_++] = c;
std::sort(ptr_, ptr_ + size_);
}
else {
arr_len = arr_len*2;
signed char *ptr_new = new signed char[arr_len];
std::copy(ptr_, ptr_ + size_, ptr_new);
delete[] ptr_;
ptr_ = ptr_new;
ptr_[size_++] = c;
std::sort(ptr_, ptr_ + size_);
}