Following is a function I wrote to get a line of definite length from a long string. The line is also word-wrapping to make sure no words are splitted:
char * getLine(char * str, int length, int start, int lenSent){
int index = 0, //Index number of the current Word
i = 0, j = 0,//Local Index
len = length, //Maximum allowed length of the line
lineLength = 0; //Length of the current line
//Character pointers
/***************************************************************/
//Line containing data to be returned to the calling program
char * line;
try {
line = new char[length + 5];
}
catch (std::bad_alloc){
cerr << "Error creating blank line for getLine f(x)" << endl;
}
//Temperory characater array pointer holding the data from which line is extracted
char * temp;
try {
temp = new char[length + (length * start) + 10];
}
catch (std::bad_alloc){
cerr << "Error creating temp array for getLine f(x)" << endl;
exit(EXIT_FAILURE);
}
/***************************************************************/
//Populate the 'temp' array with usefull data
for(i = lenSent, j = 0; i < length + (length * start) + 10; i++, j++)
temp[j] = str[i];
temp[j] = '\0'; //End the string
/***************************************************************/
//Loop till the line length is equal to or less than that of the allowed length of the line
while(lineLength <= length){
//get a single word, at position 'index' from the temperory string
char * word = getWord(temp, len, index);
//If empty word is returned i.e. word is either longer than the allowed length,
//or end of the string was reached, then exit the loop
if(strlen(word) == 0)
break;
//Append 'word' to the line
for(i = lineLength, j = 0; i < lineLength + strlen(word); i++, j++)
line[i] = word[j];
//Increase length of the line by the length of the word and the follwoing space
lineLength += strlen(word) + 1;
//Insert space after the word just added to the line
line[i] = ' ';
//Decrease the allowed length, i.e. the number of character that can still fit the line,
//by the length of the word added and one space.
len -= strlen(word) + 1;
//Increase the index of the word
index++;
//Delete the character pointer to word.
delete word;
}
//End the line with a null byte
line[lineLength] = '\0';
//Delete the temporary pointer 'temp'
delete temp; //<- This causes a HEAP CORRUPTION
//exit and return line
return line;
}
Can someone tell me what I'm missing here thats screwing up the temp variable and corrupting heap?
Thanks