As part of a BookGroup
class that manages an array of Book
objects, I'm asked to create a void add(Book* b)
member function that adds the given Book
b to an array of books in its correct place (from oldest to most recent year of publication). I'm required to shift the elements in the array towards the back of the array to make room for the new element in its correct place. I am not allowed to simply add to the end of the array and then sort or use any sorting function/sorting algorithm on the array.
I tried testing my add function and I get a seg fault. My approach was to add any new book at the end of the array and if that specific book's publication year was older (number is less) than the last book in the array, I would make the two books swap places. If not, the book would stay in the same spot at the very end of the array. I then continue this process.
I don't know what's causing the seg fault. As a side note, I was wondering if I'm supposed to use the delete function at any point in add()
? I did a valgrind check on my compiler and it says there are a bunch of bytes lost somewhere in my program. My guess is that a good chunk of the bytes are probably coming from the add function, but I'm not sure and just wanted to double check.
bookCollection
is supposed to be a statically allocated array of Book
object pointers. There are two classes - Book.cc and BookGroup.cc.
I decided to show all of my code so people can compile it, but please post only what is necessary and refrain from posting all of it in the answers below.
BookGroup.cc:
#include <iostream>
#include <iomanip>
using namespace std;
#include "BookGroup.h"
BookGroup::BookGroup(int n){
numOfBooks = n;
}
void BookGroup::add(Book* b){
if(numOfBooks != MAX_BOOKS){
if(numOfBooks == 0){
bookCollection[0] = b; //add first element
++numOfBooks; //increase numOfBooks by 1 and go to next statement
}else{
for(int i = numOfBooks-1; i >= 0; --i){ //start at end of array and work towards front where lowest years are
if(b->getPubYear() < bookCollection[i]->getPubYear()){
bookCollection[i + 1] = bookCollection[i]; //swap positions if b is lower than last element
bookCollection[i] = b;
}else{
b = bookCollection[i + 1]; //otherwise stay in the same spot (keep b at the end)
//break;
}
}
++numOfBooks;
}
}
cout<<"Book could not be added to collection. No more space "<<endl;
}
BookGroup.h:
#ifndef BOOKGROUP_H
#define BOOKGROUP_H
#define MAX_BOOKS 15
#include <string>
using namespace std;
class BookGroup
{
public:
BookGroup(int);
BookGroup(BookGroup&);
~BookGroup();
void print();
void add(Book*);
Book* bookCollection[MAX_BOOKS];
private:
int numOfBooks;
};
#endif
Book.cc: https://pastebin.com/9swrwYgx
Book.h: https://pastebin.com/mqDn2C30
makefile: https://pastebin.com/xHKDsVL1
main: https://pastebin.com/TBzyduMC
When I try to run it:
Declaring two book groups...
Initializing two book groups...
-- default Book ctor: Peter pan year: 1982
Segmentation fault