for my CS215 course, I was given a class called String215 which is a basic string class to help in the understanding of dynamic memory allocation and pointer arithmetic with char arrays.
The class was given to me in a very basic skeleton form with prototypes but no implementations, along with a test function to test my implementations. I CAN NOT use any C String functions in this assignment.
The part of the program which is troubling is the append function, which just appends a parameter string215 object to the end of the current string215 object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// Add a suffix to the end of this string. Allocates and frees memory.
void string215::append(const string215 &suffix)
{
int dataLength = str_len(data);
char *output = new char[dataLength+suffix.length()+1];
char *outTemp = output;
char *dataTemp = data;
for(int x = 0; x < dataLength; x++) {
*output = *dataTemp;
output++;
dataTemp++;
}
for(int y = 0; y < suffix.length(); y++) {
*output = suffix.getchar(y);
output++;
}
*output = '\0';
data = outTemp;
}
|
Execution of this function causes a heap corruption:
Debug Error!
Program: [Source path]
HEAP CORRUPTION DETECTED: after Normal block (#136) at 0x005C4CC0.
CRT detected that the application wrote to memory after end of heap buffer. |
Here is the description of the append function:
Add the suffix to the end of this string. Allocates a new, larger, array; copies the old contents, followed by the suffix, to the new array; then frees the old array and updates the pointer to the new one. |
I've stepped through my append function using the debugger and still can't seem to figure out what's wrong with it.
The error changes to a Debug Assertion Failed as soon as I try and free up the memory I allocated for output.
Adding:
delete[] output;
after I assign outTemp to data generates:
Debug Assertion Failed!
Program: [Source path]\dbgdel.cpp
Line: 52
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
...
Abort || Retry || Ignore |
You can look at the entirety of my code here:
Any help at all would be greatly appreciated!
Thanks, RAW-BERRY