使用查找和替换程序检测到堆损坏

Heap Corruption Detected with find and replace program

本文关键字:检测 损坏 程序 替换 查找      更新时间:2023-10-16

我有一个查找和替换程序,有时可以工作,但后来我开始得到这个错误:HEAP CORRUPTION DETECTED:在地址处的Normal块(#142)之后。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;
}
} 

您可能需要考虑当您输入字符串"a",然后用类似this string is way too long的内容替换a时会发生什么。

您会发现,虽然C++字符串可以很好地处理扩展,但C字符串却不能这样。当你执行这一行时:

strcpy(input_str, input_string.c_str());

扩展后的字符串被复制到(非常未扩展的)input_str缓冲区,从而导致堆损坏。

C++字符串的整个是为了防止很多人在使用更原始的C字符串时遇到问题,所以我不完全确定为什么要恢复到旧方法。在任何地方使用C++字符串都要好得多。否则,您必须确保自己管理空间。

如果非要我猜的话,我会说这是因为你用一个没有空间的大字符串替换了一个小字符串——特别是破坏了optimize():中这一行的堆

strcpy(input_str, input_string.c_str());