0

I have a find and replace program that works sometimes but then I started to get this error: HEAP CORRUPTION DETECTED: after Normal block (#142) at address. CRT detected that the application wrote to memory after end of heap buffer.

I am not too sure what the problem is because every time I allocated memory I also deallocated it. I must be missing something. If anyone has any advice that would be greatly appreciated. Here is the code in full:

#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"に置き換えるとどうなるかを考えてみてください。athis 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

推測する必要がある場合は、小さな文字列を、余裕のない大きな文字列に置き換えたことが原因であると言えます。具体的には、次の行でヒープを破損していますoptimize()

strcpy(input_str, input_string.c_str());

于 2013-07-09T00:37:31.807 に答える