尝试删除字符数组时崩溃

时间:2013-07-25 01:52:47

标签: c++ arrays char new-operator delete-operator

当它到达test2需要删除String对象的删除部分时,它会崩溃。我不确定它崩溃的原因。它说“Debug Assertion failed!”。我是否错误地删除了动态的alloacted char数组?

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

1 个答案:

答案 0 :(得分:4)

要复制数组内容,请不要复制指针,而不是

buf = s;

你想复制内容

memcpy(buf,s, sLength+1);

这会保留您为以后删除而分配的buf