当它到达test2需要删除String对象的删除部分时,它会崩溃。我不知道它为什么崩溃。它说“调试断言失败!”。我是否删除了动态的异步字符数组?尝试删除字符数组时发生崩溃
strdrv.cpp:
#include <iostream>
#include <stdlib.h>
#include "strdrv.h"
int main() {
test2();
return 0;
}
void test2() {
cout << "2. Testing S2: String one arg (char *) constructor."
<< endl << endl;
csis << "2. Testing S2: String one arg (char *) constructor."
<< endl << endl;
String s2("ABC");
s2.print();
wait();
}
String.cpp:
#include "String.h"
#include <iostream>
using namespace std;
String::String(char* s) {
int sLength = 0;
for (int i = 0; s[i] != '\0'; i++) {
sLength++;
}
buf = new char[sLength+1];
dynamicallyAlloc = true;
buf = s;
length = sLength;
/*buf[length] = '\0';*/
}
String::~String() {
if(dynamicallyAlloc)
delete []buf;
}
STRING.H:
#ifndef _STRING_H
#define _STRING_H
#include <iostream>
using namespace std;
class String {
protected:
bool dynamicallyAlloc;
char nullChar;
int length;
char* buf;
void calculateStringLength();
public:
String();
String(char*);
String(char);
String(int);
String(const String&);
String(char, int);
~String();
int getLength() const;
char* getString() const;
String& operator=(const String&);
String& operator=(const char*);
String& operator+=(const String&);
String operator+() const;
char& operator[](int);
String& operator++();
String& operator--();
String operator++(int);
String operator--(int);
String substr(int, int);
void print();
friend String operator+(const String&, const String&);
friend String operator+(const String&, const char*);
friend String operator+(const char*, const String&);
friend String operator+(const String&, char);
friend String operator+(char, const String&);
friend char* operator+(const String&, int);
friend char* operator+(int, const String&);
friend int operator==(const String&, const String&);
friend int operator!=(const String&, const String&);
friend int operator<(const String&, const String&);
friend int operator<=(const String&, const String&);
friend int operator>(const String&, const String&);
friend int operator>=(const String&, const String&);
friend ostream& operator<<(ostream& os, const String& s1);
};
#endif
在分配'buf'后,你给它分配's'。所以你泄漏分配的缓冲区,而是让'buf'指向传递给构造函数的字符串。销毁时,您尝试删除该字符串。所以不是'buf = s;',我想你想要像'strcpy(buf,s);'这样的东西。当然,使用'std :: string'会更安全。 – jogojapan
我已投票表示搁置此问题,因为代码示例太复杂,无法成为[最小代码示例](http://sscce.org/)。 – jogojapan
你有太多的重载。让构造函数做一些工作。 – chris