First time with an account here but I've enjoyed the site a fair deal.
I'm attempting to create a function that receives a const char array and returns a portion indicated of said array. Along with the array the function receives two values indicating the index of the first character in the portion to be extracted and the index of the last character.
The tricky part about what I'm attempting is that I'm creating a temporary array variable to hold this portion inside a function and given that the size of the portion isn't guaranteed to be a constant I'm using dynamic memory to allocated the necessary space and here's where I'm having my issue.
Whenever the function returns any information the function ends and the program doesn't have a chance of deallocating the spared memory. If I delete the variable I'm unable to return the information.
I tried creating a separate pointer variable to point to the information after it's formed but once the memory is deallocated the information doesn't seem to be able to be recovered.
Program with issues dealllocating:
char* seperateString(const char* a, int b, int c) {
// This is simply to assure that I don't allocated a negative size
if (b < c) {
cout << "***Error with \"seperateString\" function***" << endl << endl;
return '\0';
}
char* seperated = new char[c - b + 2];
int i = 0;
int j = b;
for (; i <= c - b; i++)
seperated[i] = a[j++];
seperated[i] = '\0';
char* send = seperated;
delete[] seperated;
return send;
}
int main() {
cout << "Program Iniciated." << endl << endl;
const int a = 6, b = 11;
const char* toBeSeperated = "Hello there, I have missed you.";
char *ari = seperateString(toBeSeperated, 6, 11);
cout << "Sentence is: " << toBeSeperated << endl << endl
<< "Extracted portion is: " << ari << endl << endl;
cin.get();
return 0;
}
Program working as intended in the main function.
int main() {
cout << "Program Iniciated." << endl << endl;
// variable a and b hold the beginning and last index values of the portion
// that is wanted to extract.
const int a = 6, b = 11;
// This is an example sentence |------| this is the portion being extracted.
const char* toBeSeperated = "Hello there, I have missed you.";
// variable holding extracted portion.
// created with the size necessary to hold the portion plus a \0.
char* seperated = new char[b -a +2];
//Given that a and b are index values 1 has to be added for size
//Additionally an extra space is require for \0
//i is held outside the for loop to allow to access it after it completes the cycle
//so it's able to assing \0 after the last character.
int i = 0;
//j holds the value of the first index
int j = a;
for (; i <= b - a; i++)
seperated[i] = toBeSeperated[j++];
seperated[i] = '\0';
cout << "Sentence is: " << toBeSeperated << endl << endl
<< "Extracted portion is: " << seperated << endl << endl;
delete[] seperated;
cin.get();
return 0;
}
In closing, this is about preventing memory leakage.