Growable String Array - Getting Seg Fault
Dec 18, 2014 at 6:26am UTC
Hi all,
As stated in the title, I'm just trying to write a class with a growable string array. I'm not worried about overwriting old words, and the unused indexes of the new string arrays are fine just being empty strings.
The seg. fault is happening in the set function (on line 113, to be exact), and I'm not sure why. Let me know if you guys see anything!!
Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
#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 + 1;
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);
}
Last edited on Dec 18, 2014 at 6:27am UTC
Dec 18, 2014 at 6:51am UTC
1 2 3 4 5 6 7
for (int i = 0; i < newSize; i++)
{
newWord[i] = word[i];
//size of "newWord" is "newSize" > size of "word" (size)
//so when i is "newSize - 1" === "index",
//word[index] is classifiied.. :)
}
Dec 18, 2014 at 7:01am UTC
Thanks!!!
Topic archived. No new replies allowed.