Name as "321_HW3_3". This
program runs out of memory, but it only ever uses about 60MB of memory,
and NetRun lets you use 100MB. Fix the allocateBufs routine to
not run out of memory. It may help to read this new lecture note on fragmentation. There are lots of other ways to do this, including:
- Placement new on the "llNode" objects, as shown, into a preallocated space.
- Allocating all the "buf" objects before the loop
- Allocating all the "llNode" objects before the loop
- Doing a (bizarre) "char *c=new
char[50000];new char[1];delete[] c;" beforehand to leave a 50KB hole
for the llNode objects!
#include <new> /* needed for placement new */
/* One linked-list node. Points to an allocated buffer */
struct llNode {
llNode *next; /* Points to next entry in the linked list */
char *buf; /* allocated buffer */
/* Constructor: create a linked-list node */
llNode(llNode *next_,char *buf_)
:next(next_), buf(buf_) {}
/* Return number of nodes in linked list */
int count(void) {if (next) return 1+next->count(); else return 1;}
/* Free all the allocated buffers in this list */
void freeBuf(void) {
delete[] buf; buf=0;
if (next) next->freeBuf();
}
};
/* Allocate number different buffers of this size.
Return a linked list of the allocated buffers. */
llNode *allocateBufs(int size,int number) {
llNode *head=NULL;
char *nodeStorage=new char[sizeof(llNode)*number];
for (int i=0;i<number;i++) {
char *buf=new char[size];
llNode *n=new(nodeStorage) llNode(head,buf); /* placement new */
nodeStorage+=sizeof(llNode); /* skip over n's space */
head=n;
if ((i%100)==0)
printf("Allocated %dth %d bytes at %p, link at %p\n",
i,size,buf,n);
}
return head;
}
/* Use the buffers, then throw them away. */
void processBufs(llNode *l,int size) {
llNode *cur=l;
while (cur!=0) {
cur->buf[size-1]='K';
cur=cur->next;
}
l->freeBuf();
}
/* You MAY NOT modify the foo routine... */
int foo(void) {
int nLinks=0;
try {
llNode *lA=allocateBufs(60000,1000);
processBufs(lA,60000);
llNode *lB=allocateBufs(61000,1000);
processBufs(lB,61000);
nLinks=lA->count()+lB->count();
/* don't worry about throwing away the lA and lB links... */
} catch (...) {
printf("Error allocating memory!\n");
}
return nLinks;
}