#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct
{
int start_block;
int num_blocks;
} FileAllocation;
typedef struct node
{
int block_index;
struct node *next;
} BlockNode;
int disk[MAX_SIZE];
int disk_size = MAX_SIZE;
BlockNode *free_list = NULL;
void initializeDisk()
{
int i;
for (i = 0; i < disk_size; i++)
{
disk[i] = -1; // -1 indicates free space
}
}
int allocateLinked(int num_blocks)
{
if (free_list == NULL)
{
printf("Error: Disk is full.\n");
return -1;
}
int start_block = free_list->block_index;
BlockNode *current = free_list;
int count = 0;
while (current != NULL && count < num_blocks)
{
disk[current->block_index] = 1; // Mark block as allocated
count++;
current = current->next;
}
if (count < num_blocks)
{
printf("Error: Not enough free space.\n");
return -1;
}
free_list = current; // Update free list
return start_block;
}
void freeLinked(int start_block, int num_blocks)
{
int i;
for (i = start_block; i < start_block + num_blocks; i++)
{
disk[i] = -1; // Mark blocks as free
BlockNode *new_node = (BlockNode *)malloc(sizeof(BlockNode));
new_node->block_index = i;
new_node->next = free_list;
free_list = new_node; // Add to the beginning of free list
}
}
void displayDisk()
{
int i;
printf("Disk Status:\n");
for (i = 0; i < disk_size; i++)
{
printf("%d ", disk[i]);
}
printf("\n");
}
int main()
{
initializeDisk();
// Simulate free blocks in disk
BlockNode *temp = NULL;
int i;
for (i = 0; i < disk_size; i += 5)
{
BlockNode *new_node = (BlockNode *)malloc(sizeof(BlockNode));
new_node->block_index = i;
new_node->next = temp;
temp = new_node;
}
free_list = temp;
int allocated_block = allocateLinked(7);
if (allocated_block != -1)
{
printf("Linked allocation successful. Allocated block starting at index %d.\n", allocated_block);
}
displayDisk();
// Free the allocated space
freeLinked(allocated_block, 7);
printf("Freed the allocated block.\n");
displayDisk();
return 0;
}