/*
* List.h
*
* Created on: Dec 12, 2012
* Author: MrD
*/
#ifndef LIST_H_
#define LIST_H_
class List {
long j;
public:
List * next;
List * previous;
virtual long jj() {
return this->j;
}
List() {
next = previous = 0;
j = 0; // it still initializes it to 0 - mostly :)
}
virtual ~List() {
if (next) {
next->previous = this->previous;
}
if (previous) {
previous->next = this->next;
}
}
};
#endif /* LIST_H_ */
#include <time.h>
#include<iostream>
#include <exception>
using namespace std;
const static int EVERY = 10000;
void print(List * begin) {
List * biter = begin;
while (biter != 0) {
cout << biter << " : " << biter->previous << "," << biter->next << endl;
biter = biter->next;
}
}
void term_func() {
cout << "NO USE YOU WON'T SEE ME" << endl;
}
//void handler() {
// std::cout << "Memory allocation failed, terminating\n";
//// std::set_new_handler(nullptr);
//}
void deleteNodes(bool slow, List* iter) {
iter = iter->next; // do not delete the beginning
for (unsigned int var2 = 0; iter; ++var2) {
if ((bool) (var2 % EVERY) == slow) {
List* temp = iter->next;
delete iter;
iter = temp;
} else
iter = iter->next;
}
}
void traverse(List* iter, List* const BEGIN) {
iter = BEGIN;
long val = 0;
for (List *iter2 = BEGIN; iter2; iter2 = iter2->next) {
if (++val > 87910000) {
// print(iter);
cout << val << endl;
cout << iter2 << endl;
// return;
}
// if ((*iter).jj() && (*iter).jj() != val) {
// val = (*iter).jj();
// cout << (*iter).jj() << endl;
// }
}
}
int main(int argc, char **argv) {
cout << "size of List c++ : " << sizeof(List) << endl;
set_terminate(term_func);
// std::set_new_handler(handler);
clock_t tStart = clock();
List * ptrList = new List();
List * const BEGIN = ptrList;
unsigned long var = 0;
// try {
// while (true) {
// new int[100000000ul];
// }
// } catch (const std::bad_alloc& e) {
// std::cout << "Allocation failed: " << e.what() << '\n';
// }
try {
for (;; ++var) {
// List * ptrList2 = new List();
List * ptrList2 = new (nothrow) List();
if (!ptrList2) {
cout << "out of memory - created " << var << " nodes" << endl;
break;
}
ptrList->next = ptrList2;
ptrList2->previous = ptrList;
ptrList = ptrList2;
// if (!(var % 1000))
// cout << var << endl;
}
} catch (bad_alloc const& e) {
// there is an exception I can't catch for the life of me
// I get it around 87921000 - differing on Eclipse and cmd
// Win7 prof x64
cout << "caught : " << e.what() << endl;
// } catch (...) { //this won't work either
}
//print(BEGIN);
if (argc < 2) {
List * iter = BEGIN;
cout << "Fast delete" << endl;
deleteNodes(false, iter);
//print(BEGIN);
cout << "Fast traverse" << endl;
traverse(iter, BEGIN);
} else {
cout << "slow" << endl;
List * iter = BEGIN;
cout << "Slow delete" << endl;
deleteNodes(true, iter);
print(BEGIN);
cout << "Slow traverse" << endl;
traverse(iter, BEGIN);
}
cout << "Time taken: " << (double) (clock() - tStart) / CLOCKS_PER_SEC
<< endl;
return 0;
}