J. Doe J. Doe - 2 months ago 15
C++ Question

Memory allocation errors in C++ code

I am getting all kinds of memory errors when testing the code in the header file. Please help me by letting me know what's wrong in the same. Thank you!

The code in question is the one in the code block below. It has comments so its pretty self explanatory.

Thank you very much for your help!!!

#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

Answer

The insert() function has a number of errors when it's growing the array.

  1. It doesn't update arr_len with the new length.
  2. It's reassigning ptr_ with the new array before it has copied the values from the old array, and then it's copying the array to itself. You need to use a temporary variable for this.
  3. It never frees the old array.

This fixes those problems:

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_);
    }