I am trying to do some practice for memory allocation.
I have the below code which is working but have two questions.
Where do I have to use delete [ ] to free the memory after allocating?
Why is the output for this code at function when using show() function is 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 the output:
This is a car and it has the following functions: CDcar, and its speed is 0 km/h
I thought the output shoud be this:
This is a car and it has the following functions: CD player with MP3, and its speed is 0 km/h
Please advise
Ideally nowhere.
newanddeleteare features of C++ that are not suitable for most code. They are error-prone and too low-level. They’re only useful for basic building blocks.The code shown could benefit from basic building blocks like
std::string,std::vector.The code shown also invokes undefined behaviour at least in one place:
Arrays are 0-based, so
function[1]is an out-of-bounds access.