Sunday, March 23, 2014

Next Fit (Memory Allocation) : OS Design

#include <iostream.h>
#include <conio.h>

//Implementing next fit memory management pattern

/*
*allocate method will be used to allocate the memory after taking user input in main
*/
void allocate(const int *blockSize, int &blocks, const int *procImageSize, int &processes)
{
int *allocVectorPro = new int[processes];
int *allocVectorMem = new int[blocks];
for(int i=0;i<processes;++i)
{
allocVectorPro[i] = -1;    //no process has yet been allocated
allocVectorMem[i] = -1; //no memory block has yet been allocated
}

int mem=0;
for(int pro=0;pro<processes;++pro)
{
for(;mem<blocks;)
{
if(blockSize[mem]>=procImageSize[pro])
{
allocVectorMem[mem]=1;
allocVectorPro[pro]=mem++;
break;
}
mem++;
}
}
cout<<"\n::::::\nAllocation complete\n::::::\n";

//displaying
for(int v5=0;v5<processes;++v5)
{
static int once=1;
if(v5>=blocks)
{
if(once)
{cout<<endl;once=0;}
cout<<"Process "<<v5+1<<" couldn't be allocated - No more memory blocks available!"<<endl;
continue;
}
if(allocVectorPro[v5]!=-1)
{
cout<<"\nProcess "<<v5+1<<" allocated to memory block "<<allocVectorPro[v5]+1;
}
else if(allocVectorPro[v5]==-1)
{
cout<<"\nProcess "<<v5+1<<" did not get into any memory block - what a shame";
}
}
}


int main()
{
clrscr();
int noBlocks = 0;
cout<<"Enter the number of memory blocks: ";
cin>>noBlocks;

int* blockSize = new int[noBlocks];
cout<<endl;
for(int v1=0; v1<noBlocks; ++v1)
{
cout<<"Enter the size of memory block "<<v1+1<<": ";
cin>>blockSize[v1];
}

int noProcs = 0;
cout<<"\nEnter the number of processes: ";
cin>>noProcs;

int* procImageSize = new int[noProcs];
cout<<endl;
for(int v2=0;v2<noProcs;++v2)
{
cout<<"Enter the size of the process image "<<v2+1<<" : ";
cin>>procImageSize[v2];
}

/*
*Dynamic resource allocation and user input code ended here
*
*
*Now call allocate to do the necessary allocation
*/

allocate(blockSize, noBlocks, procImageSize, noProcs);
getch();
return NULL;
}

No comments:

Post a Comment