分配后我在哪里可以释放内存?

Jac*_*ack 0 c++

我正在尝试做一些内存分配练习.

我有下面的代码,但有两个问题.

在分配后,我在哪里必须使用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;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

This is a car and it has the following functions: CDcar, and its speed is 0 km/h
Run Code Online (Sandbox Code Playgroud)

我认为输出应该是这样的:

This is a car and it has the following functions: CD player with MP3, and its speed is 0 km/h
Run Code Online (Sandbox Code Playgroud)

请指教

R. *_*des 6

在分配后,我在哪里必须使用delete []来释放内存?

理想情况下无处可去.new并且delete是C++的功能,不适合大多数代码.它们容易出错,而且级别太低.它们仅适用于基本构建块.

显示可以从基本的构建模块一样受益的代码std::string,std::vector.


显示的代码至少在一个地方调用未定义的行为:

function = new char [1][30];
strcpy(function[1], "CD player with MP3");
Run Code Online (Sandbox Code Playgroud)

数组是从0开始的,因此function[1]是一个越界访问.