string subscript out of range - string bubble sort - c++

First post here but I've been digging around for a solution to this bug.
I am getting an error "string subscript out of range"
PhoneBook is an array of class Contact object pointers.
static const int maxSize = 10;
Contact* phoneBook[maxSize]; //array of contact pointers
where Contact is defined as
class Contact
{
public:
Contact();
std::string firstName;
std::string lastName;
std::string name; //lName + fName
std::string phoneNumber;
std::string address;
};
Here is my bubble sort function.
void AddressBook::bubbleSort(Contact phoneBook[], int length)
{
Contact temp;
for (int i = 0; i < length; i++)//for n-1 passes
{
for (int j = 0; j < length - 1; j++)
{
if (phoneBook->name[j] > phoneBook->name[j + 1])
{
temp = phoneBook[j];
phoneBook[j] = phoneBook[j + 1];
phoneBook[j + 1] = temp;
}
}
}
}
here is addContact
void AddressBook::addContact(std::string fName, std::string lName, std::string pNumber, std::string addr)
{
if (isFull())
{
std::cout << "Is full" << std::endl;
return;
}
Contact *contact = new Contact;
contact->firstName = fName;
contact->lastName = lName;
contact->name = lName + ", " + fName;
contact->phoneNumber = pNumber;
contact->address = addr;
std::cout << contact->name + " has been added!" << std::endl;
phoneBook[length] = contact;
length++;
bubbleSort(phoneBook[maxSize], length);
}
and lastly, where i use it (source.cpp)
switch (choice)
{
case 1:
addrBook.addContact("Ty", "Le", "6191231234", "1234 State Street");
addrBook.addContact("Zak", "Zachary", "6191231234", "1234 Avenue Drive");
I know for a fact that the problem originates from the bubbleSort function because it'll work fine when I comment it out of addContact().
Here's a picture of my error
(too long to copy and paste)
FULL CODE
.h
https://pastebin.com/TrtQW8Tc
.cpp
https://pastebin.com/EaGBUe9e
source
https://pastebin.com/1BR5pXZE

This is almost a typo. Instead of indexing the name string in
if (phoneBook->name[j] > phoneBook->name[j + 1])
you want to index phonebook
if (phoneBook[j].name > phoneBook[j + 1].name)

Related

Why do I get a segmentation fault when fetching this variable?

I am pulling names as strings from a file, create a Person *p object, and put it into an array.
Then to search the array for a name but when I try to fetch the name I get a segmentation fault.
Why is this segmentation fault happening, and what can I do to fix it?
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string firstName;
string lastName;
string phoneNumber;
public:
Person();
Person(string f, string l, string n);
~Person(void);
void setName()
{
}
string getFirstName()
{
return firstName;
}
string getLastName()
{
return lastName;
}
string getNumber() { return phoneNumber; }
void print();
};
Array creation.
{
ifstream file;
file.open("phonebook.txt");
if (!file.is_open()) //Check for File Error.
{
cerr << "Failed to open file" << endl;
exit(1);
}
//Get Array Size
string line;
while (getline(file, line))
{
count++;
}
file.close();
//Create an array
Person *arrList[count];
buildArray(arrList, count);
if (uInput == "a" || uInput == "A") //To add
{
int x = addPerson();
if (x == 1)
{
count++;
}
delete[] arrList;
}
void buildArray(Person *arr[], int size)
{
string f, l, n;
ifstream file;
file.open("phonebook.txt");
for (int i = 0; i < size; i++)
{
file >> f >> l >> n;
Person *p = new Person(f, l, n);
arr[i] = p;
delete p;
}
}
The search, This is the part that has the trouble. I have tried a few different things including creating 2 Persons, and comparing their parts but whenever it goes into the .h it can not return the name.
if (uInput == "s" || uInput == "S")
{ //To Search
string f, l;
cout << "Find Who (Firstname Lastname) " << endl;
cin >> f >> l;
Person *n = new Person(f, l, "");
int i = 0;
bool found = false;
while (i <= count && found == false)
{
Person *p = new Person("", "", "");
p = arrList[i];
if (p->getFirstName() == n->getFirstName() && p->getLastName() == n->getLastName())
{
arrList[i]->print();
found = true;
delete p;
delete n;
}
i++;
}
while (i == count && found == false)
{
cout << "No results found. " << endl;
found = true;
}
}

Copying Array - Crashes After Doubling Array

I'm having some trouble with this program, I'm aware I can use a vector but I'm trying to do it only using arrays. Once the program gets to the initial array size of 1000, it should double the array (in this case to 2000) after copying the data. So for example if I had a list of 3000 names, it'd double once at 1000, then again at 2000 - making the total list 4000. I'm not entirely sure why it crashes after I double the array size. Can someone help me with this?
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
struct Information {
char functionality;
string SSN;
string name;
};
Information* person;
int numPeople = 1000;
int numRetrieved = 0;
int numArray = 0;
int numInserted = 0;
int numDeleted = 0;
void doubleArray(Information *person){
numPeople = numPeople * 2;
Information* temp = new Information[numPeople];
memcpy(temp, person, numPeople/2);
delete[] person;
person = temp;
cout << "Person 1: " << person[0].name << " " << person[0].SSN << endl;
}
//Currently not using this until I figure out the double...
void halfArray(Information *person){
numPeople = numPeople / 2;
}
void deleteInfo(Information *person, string SSN){
for(int i = 0; i < numArray; i++){
if(person[i].SSN == SSN){
for(int k = i; k < numArray-1; k++){
person[k].SSN = person[k+1].SSN;
person[k].name = person[k+1].name;
}
numArray--;
numDeleted++;
if((numArray+1) < (numPeople / 4)){
//halfArray(person);
}
}
}
}
void retrieve(Information *person, string findSSN, int lastPerson){
for(int i = 0; i < lastPerson; i++){
if(person[i].SSN == findSSN){
numRetrieved++;
}
}
}
void insert(Information *person, string SSN, string name){
if(numArray == (numPeople - 1)){
doubleArray(person);
}
bool dontInsert = false;
for(int i = 0; i <= numArray; i++){
if(person[i].SSN == SSN){
dontInsert = true;
}
}
if(dontInsert){
dontInsert = false;
}else{
person[numArray].SSN = SSN;
person[numArray].name = name;
numArray++;
numInserted++;
}
}
int main(int argc, char* argv[]) {
person = new Information[numPeople];
char firstLetter;
string SSN, firstName, lastName, name;
fstream input(argv[1]);
for(int i = 0; !input.eof(); i++){
input >> firstLetter >> SSN >> firstName >> lastName;
name = firstName + " " + lastName;
switch(firstLetter){
case 'd':{
deleteInfo(person, SSN);
break;
}
case 'i':{
insert(person, SSN, name);
break;
}
case 'r':{
retrieve(person, SSN, numArray);
break;
}
}
}
input.close();
}
You delete the memory that the Information* points at, but you have a copy of that pointer, and assigning it to your temp variable has no effect outside of doubleArray.
Let's say that the value of person passed in is 0xC001C001;
void doubleArray(Information *person){
numPeople = numPeople * 2;
Information* temp = new Information[numPeople];
memcpy(temp, person, numPeople/2);
delete[] person;
person = temp;
cout << "Person 1: " << person[0].name << " " << person[0].SSN << endl;
}
You create a new pointer temp which has a value of 0xBAD1BAD1. You delete person (0xC001C001), then assign 0xBAD1BAD1 to person. Execution then continues in the insert function ...
void insert(Information *person, string SSN, string name){
if(numArray == (numPeople - 1)){
doubleArray(person);
}
bool dontInsert = false;
for(int i = 0; i <= numArray; i++){
if(person[i].SSN == SSN){
dontInsert = true;
}
}
The person variable here still has the value 0xC001C001, which has been deallocated. Your program blows up when you deference person with person[i].SSN.
When you want to change a pointer, the classic pattern is to pass a pointer pointer. (Two star programming)
void redo(P** p)
{
P* temp = new P();
delete *p;
*p = temp;
}

Sorting book title alphabetically

I use a for loop and if-else statement to try to sort the titles of the books alphabetically. However, I am facing some errors under the returnlistofBooks method. Is there any ways to fix this problem?
voidBookshelf::voidBookshelf(vector <Book*> listofBooks){
this->listofBooks = listofBooks;
}
void voidBookshelf::addBook()
{
int ID;
string Title;
string Author;
for (int i = 1; i <= 5; i++)
{
cout << "Book#"<< i << ":" << endl;
cout << "Enter an ID:";
cin >> ID;
cout << "Enter a title:";
cin >> Title;
cout << "Enter an author:";
cin >> Author;
Book *mybook = new Book(ID, Title, Author); //book object
listofBooks.push_back(mybook);
}
}
void returnListofBooks(int count, string name)
{
Book temp;
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count - i; j++)
{
if (books[j].author > books[j + 1].author)
{
//swapping the instances themselves, but still comparing by the member.
temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
int main(){
voidBookshelf * myBookshelf = new voidBookshelf;
myBookshelf->addBook();
myBookshelf->returnListofBooks();
return 0;
}
you can check here for sort function!it is quite simple!
go to:
http://www.cplusplus.com/articles/NhA0RXSz/
An easy method to allow sorting is to overload operator< in your class:
class Book
{
public:
bool operator< (const Book& b)
{
return author < b.author;
}
private:
std::string author;
};
If you want to sort by other fields, you will need to write a custom comparison operator:
class Book
{
std::string title;
friend bool order_by_title(const Book& a, const Book& b);
};
bool order_by_title(const& Book a, const Book& b)
{
return a.title < b.title;
}
std::vector<Book> library;
//...
std::sort(library.begin(), library.end(), order_by_title);

Program crashes due to undefined behavior

So I'm writing a program that creates a library for a collection of CDs and displays them. My program compiles but crashes whenever I write an array of pointers to songs from a file into structs contained within an array shown here:
//Get song array
for (int a = 0; a < num_songs; a++)
{
getline (infile, line);
sub = line.c_str();
word = createString(sub);
length = substr(word, -1, 5);
title = substr(word, 5, strlen(sub));
cd->song_array[a] = createSong(title,length);
destroyString(word);
}
I think it's due to undefined behavior, here's the .cpp file that this is happening in.
#include <iostream>
#include "CDs.h"
#include "CD.h"
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
//Creates a collection of CDs
CDs* createCDs(const char* file_name)
{
//Declare variables and allocate memory
int max_cds = 50;
CDs* collection = new CDs;
collection->max_cds = max_cds;
CD** cd_array = new CD*[max_cds];
int num;
int sentinel = 0;
String* word;
string line;
CD* cd;
const char* sub;
String* length;
String* title;
//Open .txt file
ifstream infile;
infile.open(file_name);
if (infile.is_open())
{
while (infile.good())
{
for (int i = 0; i < max_cds; i++)
{
//Get the artist from .txt file
cd = cd_array[i];
getline (infile, line);
sub = line.c_str();
word = createString(sub); //Create string from infile line
cd->artist = word;
destroyString(word);
//Get the Title of the album from file
getline (infile, line);
sub = line.c_str();
word = createString(sub);
cd->title = word;
destroyString(word);
//Get the Year of the album from file
infile >> num;
cd->year = num;
//Get the Rating
infile >> num;
cd->rating = num;
//Get number of tracks
int num_songs;
infile >> cd->num_tracks;
//Get song array
for (int a = 0; a < num_songs; a++)
{
getline (infile, line);
sub = line.c_str();
word = createString(sub);
cout << "SHIT" << endl;
length = substr(word, -1, 5);
title = substr(word, 5, strlen(sub));
cd->song_array[a] = createSong(title,length);
destroyString(word);
}
cd_array[i] = cd;
sentinel++;
}
}
}
else
{
cout << "file did not open";
}
collection->cd_array = cd_array;
collection->num_cds = sentinel;
collection->max_cds = max_cds;
return collection;
}
I have no idea what to do to make this run, If someone could help that would be amazing.
edit - I didn't give the .cpp that is included and has some of the functions used
#include <iostream>
#include <cstring>
#include "String.h"
using namespace std;
//Function that creates a string
String* createString(const char* char_array)
{
//Allocate memory for a pointer to String struct
//String* string;
String* string = new String;
//Write the char_array to String struct
int length = strlen(char_array);
char array[30];
for (int i = 0; i <= length; i++)
{
array[i] = char_array[i];
string->array[i] = array[i];
}
return string;
}
//Function that displays the string
void displayString(String* str)
{
for (int i = 0; i < strlen(str->array); i++)
{
cout << str->array[i];
}
cout << endl;
}
//Function that destroys the string
void destroyString(String* str)
{
delete str;
str = NULL;
}
int find(String* str, char delimiter, int start)
{
for (int i = start; i <= strlen(str->array); i++)
{
if (str->array[i] == delimiter)
{
return i;
}
}
cout << "No occurences of delimiter were found" << endl;
return -1;
}
String* substr(String* str, int start, int end)
{
String* new_str = new String;
int count = 0;
for (int i = start + 1; i < end - 1; i++)
{
new_str->array[count] = str->array[i];
count++;
}
return new_str;
}
void compare(String* str1, String* str2)
{
if (str1->array < str2->array)
{
cout << str1->array << " is less than " << str2->array << endl;
}
if (str1 > str2)
{
cout << str2->array <<" is less than " << str1->array << endl;
}
if (str1 == str2)
{
cout << "The strings are equal" << endl;
}
}
You never allocate memory for the effective CD. You just allocate an array of pointers to CDs (cd_array). This means you have an array of pointers, pointing to unkown memory locations.
The best way to ensure no such bad access is possible, is to not dynamically allocate memory. Just use CD cd_array[max_cds] and work with that. (Use call by reference, if you need to pass this to a function.)
You need to add the following lines:
//Get the artist from .txt file
cd_array[i] = new CD;
cd = cd_array[i];
.....
You should de-allocate the memory once finished using them
for(...)
delete cd_array[i];
delete []cd_array;

Deleting a record from array of pointers of my own class type

I have created an Employee class:
class Employee {
private:
int idNumber;
string name, department, position;
public:
Employee() {
idNumber = 0;
name = department = position = "";
}
Employee(string n, int idn) {
name = n;
idNumber = idn;
department = position = "";
}
Employee(string n, int idn, string dep, string pos) {
name = n;
idNumber = idn;
department = dep;
position = pos;
}
void setName(string n) {
name = n;
}
void setidNumber(int idn) {
idNumber = idn;
}
void setDepartment(string dep) {
department = dep;
}
void setPosition(string pos) {
position = pos;
}
string getName() {
return name;
}
int getidNumber() {
return idNumber;
}
string getDepartment() {
return department;
}
string getPosition() {
return position;
}
};
Now, i created a 2D array of Pointers of type Employee:
int n=2;
Employee **p = new Employee * [n];
for (int i=0; i < n; i++)
p[i] = new Employee;
I stored two records successfully as under:
Name ID Number Department Position
FS 30 CS BS
AT 27 CS BS
I have this code to delete the record of Employees:
string del_name;
int flag = 0;
cin.ignore();
cout << "Enter name: ";
getline(cin, del_name);
for (int i=0; i < n; i++) {
while (del_name == p[i]->getName() && i < n) {
if (del_name == p[i]->getName()) {
delete p[i];
p[i] = NULL;
--k;
++flag;
cout << "Record deleted." << endl;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
cout << "No record found having name " << del_name << "." << endl;
Now, What's the problem:
If a record is found at multiple times. It deletes successfully even if all the records gets deleted.
But if ALL the records are unique and I delete the records one by one and all the records get deleted in this way then the program gets terminated.
Also, is there any other optimized approach to delete records without using VECTORS.
I hope i have clearly explained my problem. I can provide further details if needed.
Thank you for your time
First, usage of std::vector<> or some other container object is the way to go about this. If you can write code that beats (in terms of speed) written by professional library writers, then go ahead.
Second, what is your goal? If it's to simply deallocate entries in that array depending on some criteria, the loop you wrote is overly complex.
bool recordDeleted = false;
for (int i=0; i < n; ++i)
{
if (del_name == p[i]->getName())
{
delete p[i];
p[i] = NULL;
recordDeleted = true;
}
}
if ( !recordDeleted )
{
// record not found
}