簡體   English   中英

C ++如何刪除本地分配的char數組?

[英]C++ how to delete local allocated char array?

我編寫了一個函數,該函數接收一個char指針作為參數,然后構建一個包含該參數char的新動態分配的char數組。然后,它返回新的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
    }

我在main中聲明一個char指針,然后使其指向從read_string函數返回的char數組。它輸出我想要的內容,但是如果我想釋放內存,它將給我運行時錯誤。如何釋放內存如果我不再需要使用Pchar了嗎?

編輯:謝謝大家提供的非常有幫助的答案。我已經成功解決了這個問題。

您的特定問題是一個錯誤的錯誤:

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;
}

您需要分配更多的內存以為EOS字符留出空間:

str = new char[strlen(pstr)+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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM