test2가 String 객체를 삭제해야하는 부분을 삭제하면 오류가 발생합니다. 나는 왜 그것이 충돌하는지 잘 모르겠습니다. "디버그 어설 션이 실패했습니다!"라고 표시됩니다. 내가 동적으로 alloacted 문자 배열을 잘못 삭제하고 있습니까?문자 배열을 삭제하려고 할 때 오류가 발생합니다.
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