P
__PPS__
Hello, I'm a university student and I'm preparing for my final today.
I'm reading course notes, I found completely strange piece of code. It
makes me laugh, I think the teacher needs to prepare herself for this
course.
so I ask for your point of view.
here's the piece of code:
Memory management by client!!
// Listing 9.4. Memory management by client rather than by server
object
class Name{
public:
char *contents; // PUBLIC pointer to dynamic memory
Name (char* name); // or Name (char name []);
void show_name();
~Name(); // destructor eliminates memory leak
};
Name::Name(char* name)// conversion constructor
....
Name::~Name(){ // destructor
delete contents; // it deletes heap memory, not the pointer
}
void Client(){
Name n1("Jones"); // conversion constructor is called
Name *p = (Name*) malloc(sizeof(Name)); // no constructor is called
p->contents = new char[strlen("Smith")+1]; // allocate dynamic memory
if (p->contents == NULL){ // 'new' was not successful
cout << "Out of memory\n"; exit(1); // give up
}
strcpy(p->contents, "Smith"); // 'new' was successful
n1.show_name(); p->show_name(); // use the objects
delete p->contents; // avoid memory leak
free (p); // notice the sequence of actions
}
// p is deleted, destructor for object n1 is called
(c) AISHY AMER CONCORDIA UNIV, ECE
I'm reading course notes, I found completely strange piece of code. It
makes me laugh, I think the teacher needs to prepare herself for this
course.
so I ask for your point of view.
here's the piece of code:
Memory management by client!!
// Listing 9.4. Memory management by client rather than by server
object
class Name{
public:
char *contents; // PUBLIC pointer to dynamic memory
Name (char* name); // or Name (char name []);
void show_name();
~Name(); // destructor eliminates memory leak
};
Name::Name(char* name)// conversion constructor
....
Name::~Name(){ // destructor
delete contents; // it deletes heap memory, not the pointer
}
void Client(){
Name n1("Jones"); // conversion constructor is called
Name *p = (Name*) malloc(sizeof(Name)); // no constructor is called
p->contents = new char[strlen("Smith")+1]; // allocate dynamic memory
if (p->contents == NULL){ // 'new' was not successful
cout << "Out of memory\n"; exit(1); // give up
}
strcpy(p->contents, "Smith"); // 'new' was successful
n1.show_name(); p->show_name(); // use the objects
delete p->contents; // avoid memory leak
free (p); // notice the sequence of actions
}
// p is deleted, destructor for object n1 is called
(c) AISHY AMER CONCORDIA UNIV, ECE