- #1
punx
- 7
- 0
Homework Statement
I am working on a program that reads in names (strings), sorts them, and then later is searchable. The problem I am having is this. When I enter the first 20 elements of the array, everything works fine. When I enter the 21 element (when it goes into the if loop) I get an error that says:
Debug Error!
Program: ...
HEAP CORRUPTION DETECTED: After Normal block (#118) at 0x00355930.
CRT detected that the application wrote to memory after end of heap buffer.
Abort Retry Ignore
To make it easier to read, arrayExpansion is a const int defined in the header file as 10.
CurrSize is defined at the beginning at 20.
Homework Equations
The Attempt at a Solution
Code:
char ** pNamesEntered;
char * pNameToSearch;
int numEntered (0);
int index;
int CurrSize (20);
int compareResult;
pNamesEntered = new char * [20];
do {
cout << "Enter a name to be sorted and then searched: ";
pNamesEntered [numEntered] = ReadString ();
if (numEntered >= CurrSize)
{
CurrSize += arrayExpansion;
char ** pNew;
pNew = new char * [CurrSize];
for (index = 0; index < numEntered; index++)
pNew [index] = pNamesEntered [index];
//memcpy (pNew, pNamesEntered, numEntered * sizeof (char *));
for (int index = 0; index < numEntered; index++)
delete [] pNamesEntered [index];
delete [] pNamesEntered;
pNamesEntered = pNew;
}
} while (strlen (pNamesEntered [numEntered++]) > 0);
The commented out memcpy line was my original attempt to copy the existing array to the new array. I get the same error when I use that line.
The rest of my program works great, its this one particular section that I can't get.
I suppose the question is, when you have dynamically created an array of pointers, and you have reached the limit of what you have created, how do you expand the array of pointers? I know how to make a single array bigger. This is my ReadString Function
Code:
char * ReadString ()
{
char * pChar;
char c;
int charCounter (0);
int CurrSize (arrayExpansion);
pChar = new char [CurrSize + 1];
while ((c = cin.get ()) != '\n')
{
pChar [charCounter++] = c;
if (charCounter >= CurrSize)
{
char * pTemp;
CurrSize += arrayExpansion;
pTemp = new char [CurrSize + 1];
memcpy (pTemp, pChar, charCounter);
delete [] pChar;
pChar = pTemp;
}
else;
}
pChar [charCounter] = '\0';
return pChar;
}
Any help with understanding this would be outstanding. Thanks.
Last edited: