我有一个有时可以工作的查找和替换程序,但后来我开始收到此错误:HEAP CORRUPTION DETECTED: after Normal block (#142) at address。CRT 检测到应用程序在堆缓冲区结束后写入内存。
我不太确定问题出在哪里,因为每次分配内存时,我都会释放它。我肯定错过了什么。如果有人有任何建议,将不胜感激。这是完整的代码:
#include <iostream>
#include <string>
using namespace std;
void optimize(char*, const char*, const char*);
bool oldStrValidate(char*, string);
int main()
{
string input, old_str, new_str;
bool oldStrValid = false;
string repeat;
do
{
cout<<"Enter a string: "<<endl;
getline(cin,input);
char* inputPtr = new char[input.length() +1];
strcpy(inputPtr, input.c_str());
do
{
cout<<"Enter the section of the string you wish to replace."<<endl;
getline(cin, old_str);
oldStrValid = oldStrValidate(inputPtr, old_str);
}while(oldStrValid == false);
cout<<"What would you like to replace\"" <<old_str<<"\" with?"<<endl;
getline(cin,new_str);
char* oldPtr = new char[old_str.length() +1];
strcpy(oldPtr, old_str.c_str());
char* newPtr = new char[new_str.length() +1];
strcpy(newPtr, new_str.c_str());
optimize(inputPtr, oldPtr, newPtr);
cout<<" try again? \"y\" for yes or \"n\" to quit." << endl;
cout<<" : ";
cin>>repeat;
cin.ignore();
delete [] inputPtr;
delete [] oldPtr;
delete [] newPtr;
}while(repeat == "y");
return 0;
}
void optimize( char* input_str, const char* old_str, const char* new_str )
{
string input_string(input_str);
string old_string(old_str);
string new_string(new_str);
size_t position = 0;
while ((position = input_string.find(old_string, position)) != string::npos)
{
input_string.replace( position, old_string.length(), new_string );
position += new_string.length();
}
strcpy(input_str, input_string.c_str());
cout << input_string << endl;
}
bool oldStrValidate(char* str, string searchFor)
{
string input(str);
int position = 0;
while ((position = input.find(searchFor, position)) != string::npos)
return true;
{
cout<<"the substring you enterd does not exist within the string"<<endl;
return false;
}
}