自定义 char* 插入函数多次 运行 时会出现 运行time 错误
Custom char* insert function gives runtime error when it is run multiple times
我正在尝试制作我自己的字符串 class,它叫做 MyString。我几乎没有字符串操作函数。除了插入功能外,它们都可以工作。当我多次使用插入功能时,程序崩溃(source.exe 已停止工作)。我目前正在使用 Dev C++。
MyString MyString::insert(MyString s2, int pos) {
int size = strlen(this->getptr());
if(pos > size || pos < 0){
return "Error";
}
char * ptrLeft = this->substr(0, pos);
char * ptrRight = this->substr(pos, size - pos);
strcat(ptrLeft, s2.getptr());
strcat(ptrLeft, ptrRight);
return ptrLeft;
}
这是MyString中的substr()函数class:
char * MyString::substr(int position, int length) {
char* otherString = 0;
otherString = (char*)malloc(length + 1);
memcpy(otherString, &this->getptr()[position], length);
otherString[length] = 0;
return otherString;
}
参数化构造函数(char * ptr为私有成员):
MyString::MyString(char* str){
int size = strlen(str);
ptr = new char[size];
ptr = str;
}
如果我多次执行以下操作,它有时会崩溃。
buff = buff.insert(" Text", 5);
cout << buff;
system("PAUSE");
buff = buff.insert(" Text", 5);
cout << buff;
system("PAUSE");
插入调用未分配新数组的大小。仅在第一个 substr 调用中进行 mallocing,最大为原始数组的大小
我正在尝试制作我自己的字符串 class,它叫做 MyString。我几乎没有字符串操作函数。除了插入功能外,它们都可以工作。当我多次使用插入功能时,程序崩溃(source.exe 已停止工作)。我目前正在使用 Dev C++。
MyString MyString::insert(MyString s2, int pos) {
int size = strlen(this->getptr());
if(pos > size || pos < 0){
return "Error";
}
char * ptrLeft = this->substr(0, pos);
char * ptrRight = this->substr(pos, size - pos);
strcat(ptrLeft, s2.getptr());
strcat(ptrLeft, ptrRight);
return ptrLeft;
}
这是MyString中的substr()函数class:
char * MyString::substr(int position, int length) {
char* otherString = 0;
otherString = (char*)malloc(length + 1);
memcpy(otherString, &this->getptr()[position], length);
otherString[length] = 0;
return otherString;
}
参数化构造函数(char * ptr为私有成员):
MyString::MyString(char* str){
int size = strlen(str);
ptr = new char[size];
ptr = str;
}
如果我多次执行以下操作,它有时会崩溃。
buff = buff.insert(" Text", 5);
cout << buff;
system("PAUSE");
buff = buff.insert(" Text", 5);
cout << buff;
system("PAUSE");
插入调用未分配新数组的大小。仅在第一个 substr 调用中进行 mallocing,最大为原始数组的大小