Cos Cos - 4 months ago 17
C++ Question

Trouble with swap method

I've got an issue with a swap method I'm trying to write. I'm convinced it's this section of code as it only throws an exception when the program terminates if these lines are uncommented. Comment them out and the file terminates properly.
My classes and the function I'm having problems with are below.

class WordOccurrence {
WordOccurrence(const std::string& word = "", int num = 0) { num_ = num; word_ = word; };

//Member Functions
bool matchWord(const std::string &); // returns true if word matches stored
void increment(); // increments number of occurrences

std::string getWord() const;
int getNum() const;

std::string word_;
int num_;

class WordList {
//Big 3:
WordList(int size = 0) { size_ = size; wordArray_ = size>0 ? new WordOccurrence[size] : nullptr;};
~WordList() { delete[] wordArray_; };
WordList(const WordList& list);

//Assignment Overload
WordList& operator =(const WordList& source);

//Member Functions
void addWord(const std::string &word);
friend void swap(WordOccurrence& first, WordOccurrence& second);

// void swap(WordOccurrence& lhs, WordOccurrence& rhs);
void sortList();
void printList();
WordOccurrence *wordArray_; // a dynamically allocated array of WordOccurrences
// may or may not be sorted
int size_;

and the sort function containing swap:

void WordList::sortList() {
for (int i = 0; i < size_; ++i) {
for (int j = size_; j > i; --j) {
if (wordArray_[j].getNum() < wordArray_[j - 1].getNum()) {
WordOccurrence tmp(wordArray_[j].getWord(), wordArray_[j].getNum()); //problem is
// tmp = wordArray_[j]; // is
wordArray_[j] = wordArray_[j-1]; // in
wordArray_[j-1] = tmp; // here
//swap(wordArray_[j], wordArray_[j - 1]);


I tried initializing 'tmp' to an empty object as well but that didn't make a difference either.
I also tried std::swap and it's throws the same "triggered a breakpoint" error when the program terminates. Again, the error disappears if I comment out the problem lines. Any help would be appreciated!


From examination of the code, the size_ member specifies the size of the dynamically-allocated wordArray_.

for (int j = size_; j > i; --j) {
    if (wordArray_[j].getNum() < wordArray_[j - 1].getNum()) {

This is going to run off past the end of the array, resulting in undefined behavior, and the likely crash.

j starts off being equal to size_. Since size_ is the actual size of wordArray_, and wordArray_ contains elements numbered 0 through size_-1, then wordArray_[j], on the first iteration, does not exist. That's your bug.