staticchar *SafeMalloc(size_t memoryNeeded)
{
char *pointerToEmptyMem;
if ((pointerToEmptyMem = (char *)malloc(memoryNeeded)) == NULL)
{
fputs("Out of Memory\n", stderr);
exit(EXIT_FAILURE);
}
return(pointerToEmptyMem);
}
LIST *CreateList(FILE *fp)
{
//automatic variable declaration
//char tempAddress, *obtainedWord = &tempAddress, *traverserPntr;
char obtainedWord[ARRAY_SIZE];
int astring = RETURN_VALUE, dynamicMemSize, duplicateFound, beginLinkList = 0;
LIST *currentList = NULL, *headerList = NULL, *secondTraverserList;
do
{
//Obtain the word to be processed
dynamicMemSize = 0;
do
{
astring = fgetc(fp);
if (astring < 0) break;
obtainedWord[dynamicMemSize] = (char)astring;
dynamicMemSize++;
} while ((!(astring == ' ')) && (!(astring == '\n')));
if (astring < 0) break;
obtainedWord[dynamicMemSize] ='\0';
//LINK LIST PROCESSING STARTS HERE
duplicateFound = 0;
secondTraverserList = headerList;
//Scan the entire list from the headerList until the list is NULL
if (beginLinkList)
do
{
if (!(strcmp(secondTraverserList->str, obtainedWord)))
{
secondTraverserList->count++;
duplicateFound = 1;
}
secondTraverserList = secondTraverserList->next;
} while (secondTraverserList!= NULL);
if (!duplicateFound)
{
currentList = CreateNewNode();
currentList->next = headerList;
headerList = currentList;
currentList->str = (char *)SafeMalloc(dynamicMemSize);
memcpy(currentList->str, obtainedWord, dynamicMemSize);
currentList->count = INITIAL_VALUE;
beginLinkList = 1;
}
//LINK LIST PROCESSING ENDS HERE
} while (!(astring < 0));
return(headerList);
}
2. This is the portion that gets the character one by one and put it together to make the word.
1 2 3 4 5 6 7 8 9 10 11
//Obtain the word to be processed
dynamicMemSize = 0;
do
{
astring = fgetc(fp);
if (astring < 0) break;
obtainedWord[dynamicMemSize] = (char)astring;
dynamicMemSize++;
} while ((!(astring == ' ')) && (!(astring == '\n')));
if (astring < 0) break;
obtainedWord[dynamicMemSize] ='\0';
3. I did a trace and I can see on the WATCH window the first word in the file which is "the" and I get obtainedWord "the" and dynamicMemSize equals to 4.
4. But when I reached this portion of the program where I create the List
5. on the memcpy, the resulting currentList->str is "the ^^^%%$%%%". note: dynamicMemSize = 4, I am expecting only 4 bytes. why am I getting garbage at the end of each word.