2011-10-09 78 views
1

我想刪除一個char *數組,這應該是簡單的吧? char * = new char[length];然後用delete[] char;刪除字符指針數組

另外,本人練習無法使用std::string

我得到這個錯誤:

HEAP CORRUPTION DETECTED: after Normal block (#137) 0x00794B50.
CRT detected that the application wrote to memory after end of heap buffer.

這裏是我的代碼:

class myClass 
{ 
    char * myString; 
    ... 
public: 
    myClass::myClass(const char * tempStr); 
}; 

myClass::myClass(const char * tempStr) 
{ 
    int length = strlen(tempStr); 
    myString = new char(length + 1); //+1 for null char 
    strcpy(myString, tempStr); 
    myString[length] = '\0'; 
    delete[] myString; //error occurs here 
} 

現在,我知道,這個代碼是完全不切實際的,但它仍然拋出了同樣的錯誤,我我試圖解決,所以如果我們能解決這個問題,那麼我應該在我的路上高興。從我讀過的這個應該可以嗎?我會重申,對於這個練習,我不能使用std::string

回答

7

你把括號弄亂了。它應該是:

myString = new char[length + 1]; 

方括號將創建一個數組。正常的括號將只用一個操作數來分配任何構造函數。

+0

哦,我討厭自己。非常感謝你,這工作,將標誌爲答案儘快。 – Jace