This question already has an answer here:
- What is The Rule of Three? 8 answers
I have a problem in this code. If I write StringIO::Copy(test2, test1); without delete str2; then this code gave me this output:
old test2: abc
new test2: test
Finished
*** Error in `./out': double free or corruption (fasttop): 0x0000000001180030 ***
Aborted (core dumped)
I really could not find the relation between str2 and other objects. If I add delete str2; then I don't see that error.
#include <iostream>
class String{
public:
char *Buffer = new char;
unsigned long Size;
public:
friend struct StringIO;
~String(void){
delete Buffer;
}
void inline operator=(const char *X);
};
struct StringIO{
static inline unsigned long Length(const char *X){
unsigned long Count = 0;
while(X[Count] != '\0'){
Count++;
}return Count;
}
static inline void Copy(char *X, const char *Y){
unsigned long Count = 0; if(Length(X) > Length(Y)){
while(Count <= (Length(X) - Length(Y))){
X[(Count + Length(Y))] = '\0';
Count++;
}Count = 0;
}
while(Y[Count] != '\0'){
X[Count] = Y[Count];
Count++;
}
}
static inline void Copy(String &X, const String &Y) {
if(X.Buffer != nullptr)
delete X.Buffer;
if(X.Buffer == nullptr)
X.Buffer = new char;
X.Size = Y.Size;
Copy(X.Buffer, Y.Buffer);
}
};
void String::operator=(const char *X){
this->Size = StringIO::Length(X);
StringIO::Copy(this->Buffer, X);
}
int main(void){
String test1, test2;
char *str1 = new char;
char *str2 = new char;
StringIO::Copy(str1, "test");
StringIO::Copy(str2, "abc");
test1 = str1;
test2 = str2;
std::cout << "old test2: " << test2.Buffer << std::endl;
StringIO::Copy(test2, test1); //here is the problem
std::cout << "new test2: " << test2.Buffer << std::endl;
//delete str2;
std::cout << "Finished" << std::endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire