0

我有一个有时可以工作的查找和替换程序,但后来我开始收到此错误: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;
}

} 
4

2 回答 2

2

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

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

strcpy(input_str, input_string.c_str());

扩展的字符串被复制到(非常未扩展的)input_str缓冲区中,因此您的堆损坏。

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

于 2013-07-09T00:39:17.970 回答
1

If I had to guess, I'd say it's being caused by you replacing a small string with a larger one that you don't have room for -- specifically corrupting the heap at this line in optimize():

strcpy(input_str, input_string.c_str());

于 2013-07-09T00:37:31.807 回答