home *** CD-ROM | disk | FTP | other *** search
- // Stress-Test C++ 'new' and 'delete'. Written in Borland/Turbo C++.
- // Written by George Lerner, Lerner Computer Consulting, 1991. (415) 586-6233.
- // You may copy this program freely.
-
- // Environment: Northgate 386/16, Hercules monitor, QEMM-386 v6.0, MS-DOS 5
- // Tested under DesqView 2.31, QEMM, and just MS-DOS 5.
-
- // Requires C++. Will not compile under C.
- // Borland C++: \bcpp\bin\bcc +glturboc.cfg -c -mm deltest.cpp
-
- // Easiest way to avoid this might be to overload new and delete for your
- // object, so when delete is called, the object's address is assigned NULL,
- // and global delete is not called unless the object != NULL.
-
- /* Example of this bug in an actual program I wrote:
- class EntryField : public Object {
- friend EntryForm;
- ...etc...
- };
- class EntryForm : public Wndo, Array { // my windowing class, BC++ Array
- ...etc...
- };
- // Add an EntryField to the EntryForm
- void EntryForm::add(EntryField &field) {
- ...other stuff...
- Array::add(field); // call the base class's add to do the rest of the work
- }
-
- // destructor
- EntryForm::~EntryForm(void) {
- for (int i=0; i < num_fields; i++) {
- detach(i); // AbstractArray::detach(int)
- // ABSOLUTELY REQUIRED to detach() the fields. Otherwise, the
- // fields will be deleted BOTH in ~EntryField() and in
- // ~AbstractArray(). Took me ages to trace the program hanging upon
- // executing the } of main().
- }
- // automatically calls base class destructors
- // ~Array();
- // ~Wndo();
- }
- */
-
- #include <stdlib.h>
- #include <iostream.h>
-
- void main() {
- char *s = new char[256];
- char *t;
- char c;
-
- cout << "This program stresses 'new' and 'delete'.\n";
- cout << "Shows can NOT delete something multiple times without problems!\n";
- cout <<
- "\n\n T H I S P R O G R A M C A N H A N G C O M P U T E R S ! \n";
-
- cout << "\n\nProgram starts by declaring strings s, and (unassigned) t.";
- cout << hex << "\ns=" << (long)s << "\n";
-
- int i;
- for (i=1; i <= 10; i++) {
- cout << "Count: " << i << " of 10\n";
- cout << "Delete S, new T\n";
- cout << " (T should have same address as S)\n";
- delete s;
- t = new char[256];
-
- cout << "S=" << (long) s << " T=" << (long) t << '\n';
-
- cout << "delete T, new T\n";
- cout << " (T should have same address as S)\n";
- delete t;
- t = new char[256];
- cout << "S=" << (long) s << " T=" << (long) t << '\n';
-
- cout << "delete T\n";
- delete t;
-
- cout << "--- Press Return (or Ctrl-C to Quit) ---\n";
- cin.get(c); // get a character from keyboard
- }
- }
-