簡體   English   中英

分配后必須在哪里釋放內存?

[英]Where do I have to free the memory after allocating?

我正在嘗試為內存分配做一些練習。

我有下面的代碼正在工作,但有兩個問題。

分配后,在哪里必須使用delete []釋放內存?

為什么在使用show()函數時該函數的代碼輸出為CDcar?

#include <cstdlib>
#include <new>
#include <iostream>
#include <cstring>
using namespace std;

class automobile {

    private:

        char (*function)[30];
        char *type;
        double speed;

    public:

        automobile ( );
        automobile (double , char *);
        void speed_up (double);
        void speed_down(double);
        const char * get_function ( ) const;
        void show ( );

};

automobile::automobile ( ) {

    speed = 0;
    function = new char [1][30];
    strcpy(function[1], "CD player with MP3");

    type = new char [4];
    strcpy(type, "car");

}

automobile::automobile(double spd, char * fn ) {

    int sz;

}

void automobile::show ( ) {

    cout << "This is a " << type << " and it has the following functions: " << function[1] << ", and its speed is " << speed << " km/h\n"; 

}

int main ( ) {

    automobile car;

    car.show ( );

    return 0;
}

這是輸出:

This is a car and it has the following functions: CDcar, and its speed is 0 km/h

我認為輸出應該是這樣的:

This is a car and it has the following functions: CD player with MP3, and its speed is 0 km/h

請指教

分配后,在哪里必須使用delete []釋放內存?

理想情況下無處 newdelete是C ++的功能,不適用於大多數代碼。 它們容易出錯,而且級別太低。 它們僅對基本構建塊有用。

所示代碼可從諸如std::stringstd::vector類的基本構建塊中受益。


所示代碼還至少在一個地方調用了未定義的行為:

function = new char [1][30];
strcpy(function[1], "CD player with MP3");

數組是基於0的,因此function[1]是一個越界訪問。

您應該在類的析構函數中調用delete[]

//Called when your class is destroyed.
automobile::~automobile()
{
   delete[] function;
}
  1. 您應該將delete[]用於function並在析構函數 ~automobile type (您當前沒有一個,因此必須創建它)。

  2. 關於輸出:字符為數組的定義不正確。 考慮將std::vector<string>用於此類事情(容易得多)。

您的輸出是不正確的以下B / C:

 speed = 0;
 function = new char [1][30];
 strcpy(function[1], "CD player with MP3");

這應該是

 speed = 0;
 function = new char [1][30];
 strcpy(function[0], "CD player with MP3");

當您輸出時,應該使用function[0]而不是function[1]

話雖如此,您幾乎應該始終嘗試消除對new和delete的手動調用。 它有助於提高可維護性,並有助於確保代碼異常的安全。 在這種情況下,您可以使用標准C ++庫提供的向量和字符串免費獲得此代碼。 從更一般的意義上講,您想遵循RAII慣用語 這將幫助C ++和內存管理在您的學習/職業生涯中節省幾年的時間。

在〜汽車銷毀器內部。

暫無
暫無

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

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