Search code examples
c++dr-memory

Memory Issue in C++ - UNINITIALIZED READ: reading register eax


After declaring a default constructor for this templated program I am working on:

template<typename T>
Set<T>::Set()
    : size(0), capacity(8) {
    //allocate new array
    items = new T[capacity];
}

I have a relatively inconspicuous function contains that tests for whether or not items contains a specific item in it.

template<typename T>
bool Set<T>::contains(const T& item) const {
    for (int i = 0; i < size; i++) {
        if (this->items[i] == item)
            return true;
    }
    return false;
}

It works fine when I call it in certain locations such as this function that reads through items and only adds an item if there is no other copy (part of our assignment specifications):

template<typename T>
void Set<T>::add(const T& item) {
    if (this->contains(item) == 0) {
        grow();
        items[size++] = item;
    }
}

But when I call it when attempting to overload the operator ==, I get the error in the title when I run it through DRMemory

template<typename T>
bool Set<T>::operator==(const Set<T>& other) const {
    int count = 0;
    for (int i = 0; i < size; i++) {
        if (this->contains(other.items[i])) {
           count++;
        }
    }
    if (count == size)
        return true;
    return false;
}

Solution

  • for (int i = 0; i < size; i++) {
        if (this->contains(other.items[i])) {
           count++;
        }
    }
    

    size should be other.size. Otherwise other.items[i] in the loop may be out-of-bounds if size > other.size.

    Similarly size in the later check needs to be other.size as well.

    On the other hand, you need to add a test for size == other.size anyway to make sure that the sets are really equal. If you put that at the beginning, it won't matter whether you use size or other.size later.

    Btw. instead of using count to count the identical elements, you can just return false as soon as one .contains fails.