I am learning C++ coming over from Objective-C / C, and for a dummy project I want to load the words from the /usr/share/dict/words file stored on Mac OS X machines.
The idea is to load the file and get each word into an array, so I have an array of type string.
But I'm having trouble working correctly with dynamic memory with my arrays - using new and delete. I've added some of the code below, if anyone could help out...
And so I'm getting a memory error:
word:: A
word:: a
word:: aa
word:: aal
definitions(2758) malloc: *** error for object 0x100103b90: incorrect
checksum for freed object - object was
probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Load words:
string* Definition::loadWords()
{
int arrayLength = 0;
arrayOfWords = new string[arrayLength];
ifstream file;
file.open("/usr/share/dict/words");
if(file.is_open())
{
while(file.good()){
string word;
getline( file, word );
this->addWord(word, arrayOfWords, &arrayLength);
}
}
file.close();
cout << endl << "There are " << arrayLength << " words" << endl;
return arrayOfWords;
};
Add words to array:
void Definition::addWord(string newWord, string currentArray[], int* arrayLength)
{
cout << endl << "word:: " << newWord;
string *placeholderArray = new string[*arrayLength + 1];
placeholderArray[*arrayLength + 1] = newWord;
for(int i = 0; i < *arrayLength; i++){
placeholderArray[i] = currentArray[i];
}
(*arrayLength)++;
currentArray = placeholderArray;
delete [] placeholderArray;
}