2015-04-03 213 views
0

我寫了一個函數,它接收一個char指針作爲參數,然後構建一個新的動態分配char數組,它包含該參數char.Then,它返回新的char數組。 這是函數:C++如何刪除本地分配的char數組?

char* read_string(char *pstr) 

    { 
     char *str; 
     str = new char[strlen(pstr)];//allocate memory for the new char 
     str[strlen(pstr)] = '\0'; 
     for(unsigned i=0;i<strlen(pstr);i++)//build the new char 
      str[i]=pstr[i]; 
     return str;//then return it 
    } 

在主我有:

int main() 

    { 
     char *Pchar = read_string("Test"); 

     cout<<Pchar;// Outputs "Test" 

     delete [] Pchar;//"Program received signal SIGTRAP, Trace/breakpoint trap." error 
    } 

我在主聲明一個字符指針,然後使之指向從read_string function.It返回的字符數組輸出我想要的,但如果我想釋放內存,它會給我運行時錯誤。如果我不需要使用Pchar,我可以釋放內存?

編輯:謝謝你所有的非常豐富的答案。我已經成功地解決了這個問題。

+1

你還沒有爲空字符,'STR [1的strlen(PSTR)分配足夠的內存]'超越界限。 – emlai 2015-04-03 19:24:42

+0

@ zenith我該如何糾正? – xQd 2015-04-03 19:25:54

+4

不要做任何這些廢話。使用std :: string。 – 2015-04-03 19:25:58

回答

1

您需要分配更多的內存來對EOS字符空間:

str = new char[strlen(pstr)+1]; 
1

您的具體問題是差一錯誤:

str = new char[strlen(pstr) + 1]; 
//       ^^^^ need one more for the '\0' 
str[strlen(pstr)] = '\0'; 

一般來說,因爲這是C++而不是C,它會更好,所以調用者知道所有權語義返回一個智能指針指針是:

std::unique_ptr<char[]> read_string(char *pstr) 
{ 
    std::unique_ptr<char[]> str(new char[strlen(pstr) + 1]); 
    // rest as before 
    return str; 
} 
1

似乎由於分配的字符串的長度不正確而發生錯誤。 你必須使用下面的記錄來分配字符串

str = new char[strlen(pstr) + 1];//allocate memory for the new char 
    str[strlen(pstr)] = '\0'; 

功能可以看看下面的方式

char* read_string(const char *pstr) 
{ 
    char *str; 
    size_t n = strlen(pstr); 

    str = new char[n + 1];//allocate memory for the new char 

    strcpy(str, pstr); 

    return str; 
} 
+0

'strcpy'也會做空終止符,所以你不需要額外的任務 – Barry 2015-04-03 19:32:38

+0

@Barry這是複製和粘貼的結果:) – 2015-04-03 19:33:40