You are on page 1of 3

Continuous Memory location

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define ALLOCATED 1
#define NOTALLOCATED 0

struct file
{
char name[25];
int size;
int allocated;
struct file *next;
};

struct file * insert (struct file *f,char *name,int size)


{
struct file *temp,*temp1;
temp = (struct file *)malloc(sizeof(struct file));
strcpy(temp->name,name);
temp->size = size;
temp->allocated = NOTALLOCATED;

if(f == NULL)
f= temp;
else
{
temp1=f;
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next = temp;
}
return f;
}

void display(struct file *f,int size)


{
struct file *temp;
int address = 0;
temp=f;
printf("\n\nMemory Blocks\n\n");
printf("\t %d |------------------------|\n",address);
while(temp!=NULL && temp->allocated == ALLOCATED)
{
address += temp->size;
printf("\t | %s %d |\n",temp->name,temp->size);
if(size == address) address--;
printf("\t%d |------------------------|\n",address);
temp=temp->next;
}
if(address<size-1)
{
printf("\t | |-1\n");
printf("\t%d |------------------------|\n",size-1);
}
}

void cma(struct file *f,int size)


{
int cpysize;
struct file *temp;
temp=f;
cpysize = size;
while(temp!=NULL)
{
cpysize -= temp->size;
if(cpysize<0)
break;
else
temp->allocated = ALLOCATED;
temp=temp->next;
}
display(f,size);
while(temp!=NULL)
{
printf("\nThe file %s of size %d is not allocated",temp->name,temp->size);
temp=temp->next;
}
}

int main()
{
int bsize,fsize;
char name[25],choice;
struct file *f = NULL;
printf("\n\nEnter memory block size:");
scanf("%d",&bsize);
while(1)
{
printf("\nEnter file name :");
scanf("%s",name);
printf("Enter the size:");
scanf("%d",&fsize);
f = insert(f,name,fsize);
printf("Do you want to continue (Y/N):");
do
{
scanf("%c",&choice); // instead of using this do .. while loop ,fflush(stdin) can be used but
its not ansi standard
}
while(choice == '\n');
if(choice == 'N' || choice == 'n')
break;
}
cma(f,bsize);
return 0;
}

OUTPUT

Enter memory block size:100

Enter file name :v1


Enter the size:20
Do you want to continue (Y/N):y

Enter file name :v2


Enter the size:40
Do you want to continue (Y/N):y

Enter file name :v3


Enter the size:30
Do you want to continue (Y/N):y

Enter file name :v4


Enter the size:45
Do you want to continue (Y/N):n

Memory Blocks

0 |------------------------|
| v1 20 |
20 |------------------------|
| v2 40 |
60 |------------------------|
| v3 30 |
90 |------------------------|
| |-1
99 |------------------------|

You might also like