使用查找和替换程序检测到堆损坏
Heap Corruption Detected with find and replace program
我有一个查找和替换程序,有时可以工作,但后来我开始得到这个错误: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());
相关文章:
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 删除字符串后C++检测到堆损坏
- 检测到堆损坏(字符串导致堆损坏)|C++
- 在C++中检测到堆损坏错误
- C++ 内存损坏检测
- 如何修复检测到堆损坏:正常阻止后
- 在复制 delete[] 数组后在 C++ 中检测到堆损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 编译器如何检测内存损坏
- 排序程序的错误(检测到堆损坏)
- 正常块错误后检测到的堆损坏
- C++ 删除数组时检测到堆损坏
- 调试错误,在C++中检测到堆损坏
- 检测到堆损坏(类方法)
- 在普通块(#164)之后检测到堆损坏
- jemalloc未检测到内存损坏
- 检测到合并排序堆损坏
- 错误: *** 检测到 glibc *** w5:双重释放或损坏(快速顶部):
- 检测到堆损坏:在正常块(#62)之后
- 在Windows上立即检测到堆损坏错误.如何