Reputation: 641
I'm trying to do a pretty basic array of strings that is dynamically growable for adding on new words to certain indexes. I need it in this basic format (i.e. can't use anything from the STL). Just a couple things to note: I'm not worried about overwriting old words, and the unused indexes of the new string arrays are fine just being empty strings.
I know my problem (seg. fault) is in my set function, but I don't know why it's happening. I'm trying to create a new, larger array of strings with the required size, populate it with the previous words, and then assign it to my class string array (after deleting the old data), and then putting in the new word at the new index.
There may be more mistakes, so feel free to be critical of any and/or all of them.
Thanks.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class GA
{
public:
GA();
GA(const GA & other);
~GA();
GA & operator=(const GA & rhs);
string get(unsigned index) const;
GA & set(unsigned index, const string & s);
private:
string * word;
int size;
};
void die(const string & msg);
int main()
{
GA w;
w.set(2, "Index Two");
w.set(6, "Index Six");
cout << w.get(2);
cout << endl;
cout << w.get(3);
}
GA::GA()
{
word = NULL;
size = 0;
}
GA::GA(const GA & other)
{
try
{
word = new string[other.size];
}
catch(const bad_alloc &){ die("Alloc. Failure");
}
size = other.size;
for (int i = 0; i < other.size; i++)
word[i] = other.word[i];
}
GA::~GA()
{
delete [] word;
}
GA & GA::operator=(const GA & rhs)
{
if (this != &rhs)
{
delete [] word;
try
{
word = new string[rhs.size];
}
catch(const bad_alloc &)
{
die("Alloc. Failure");
}
for (int i = 0; i < rhs.size; i++)
word[i] = rhs.word[i];
}
return *this;
}
string GA::get(unsigned index) const
{
return word[index];
}
GA & GA::set(unsigned index, const string & s)
{
if (index > size) // need more memory, creating another string array.
{
int newSize = index;
string * newWord = NULL;
try
{
newWord = new string[newSize];
}
catch(const bad_alloc &)
{
die("Alloc. Failure");
}
for (int i = 0; i < newSize; i++)
{
newWord[i] = word[i];
}
delete [] word;
word = newWord;
size = newSize;
}
word[index] = s;
return *this;
}
void die(const string & msg)
{
cerr << "Fatal Error: " << msg << endl;
exit(EXIT_FAILURE);
}
Upvotes: 1
Views: 156
Reputation: 6005
The index > size
should be index >= size
(or ==
if you increment by 1 all the time the index).
If for example you have an array of 5 elements, and you get an index of 5, you are trying to access the 6th element of the array.
EDIT: In addition, you are allocating an array of size equal to the index. This means that again you can index it using an index between 0
and size - 1
and not size
.
You could do this:
//Check for index being bigger or equal than the size of the array
//as the case of equality leads to an index out of array bounds!
if(index >= size){
//....
//New size must be greater than the index!
int newSize = index + 1;
//....
}
Upvotes: 2