2013-07-25 58 views
1

當它到達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 
+2

在分配'buf'後,你給它分配's'。所以你泄漏分配的緩衝區,而是讓'buf'指向傳遞給構造函數的字符串。銷燬時,您嘗試刪除該字符串。所以不是'buf = s;',我想你想要像'strcpy(buf,s);'這樣的東西。當然,使用'std :: string'會更安全。 – jogojapan

+0

我已投票表示擱置此問題,因爲代碼示例太複雜,無法成爲[最小代碼示例](http://sscce.org/)。 – jogojapan

+0

你有太多的重載。讓構造函數做一些工作。 – chris

回答

4

要複製數組的內容,不要複製的指針,而不是的

buf = s; 

你想要的內容複製

memcpy(buf,s, sLength+1); 

這將保留buf您已經分配了以後刪除。

+1

另外建議改變'sLength'和'i'鍵入'size_t'。 – chux

+0

感謝您的幫助! – randomname

相關問題