Given:
#include <iostream>
using namespace std;
struct Concrete {
char name[20];
char quest[20];
char favorite_color[13];
};
struct Concrete_with_knobs : public Concrete {
int knobs[100000];
};
Concrete * cradle() {
return new Concrete_with_knobs;
}
void grave(Concrete *p) {
delete p;
}
void tomb_of_the_unknown_allocation(void *pv) {
delete static_cast<int *>(pv);
}
void stress() {
for (int i = 0; i < 1000000; ++i) {
Concrete *p = cradle();
grave(p);
}
}
void extreme_stress() {
for (int i = 0; i < 1000000; ++i) {
Concrete *p = cradle();
void *pv = p;
tomb_of_the_unknown_allocation(pv);
}
}
int main(int, char **) {
cout << "sizeof(Concrete_with_knobs): " << sizeof(Concrete_with_knobs) << endl;
cout << "Check your memory." << endl;
char c;
cin >> c;
cout << "Stress." << endl;
stress();
cout << "Check your memory." << endl;
cin >> c;
cout << "Extreme stress." << endl;
extreme_stress();
cout << "Check your memory." << endl;
cin >> c;
return 0;
}
Summary:
- A derived class (Concrete_with_knobs) is 400K larger than its base class (Concrete).
- cradle creates a Concrete_with_knobs object on the heap, and returns its address as a Concrete pointer.
- grave takes an address as a Concrete pointer, and performs a delete operation.
- *tomb_of_the_unknown_allocation* takes an address as a void *, interprets it as the address of an int using static_cast, and performs a delete operation.
- stress calls cradle and grave a million times.
- extreme_stress calls cradle and tomb_of_the_unknown_allocation a million times.
If compiled with a conformant C++ compiler, will the system show memory leaks from either stress or extreme_stress? If so, what is an example of a compiler in general release which does in fact produce a leaky binary?