尝试删除字符数组时崩溃

Crashing when trying to delete character array

本文关键字:崩溃 数组 字符 删除      更新时间:2023-10-16

当它到达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] != ''; i++) {
    sLength++;
}
buf = new char[sLength+1];
dynamicallyAlloc = true;
buf = s;
length = sLength;
/*buf[length] = '';*/ 
}
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;

你想复制内容

memcpy(buf,s, sLength+1);

这将保留您已分配的buf,以便以后删除。