1. 背景说明
本算法基于已将磁盘分布合并并排序为升序线性表。实现示例为:磁盘扇区大小:32(可自定义),待拆分磁盘内存: [0 - 50],[60 - 100](可增加)。示意图如下:
2. 示例代码
allocateAddr.c
/* 地址分配算法 */
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
#define SEC_SIZE 32
typedef struct {
int startAddr;
int endAddr;
} IoAddr;
int GetUpBound(const IoAddr *addr)
{
int i;
for (i = 1; i <= SEC_SIZE; ++i) {
if ((addr->startAddr + i) % SEC_SIZE == 0) {
return i - 1;
}
}
return 0;
}
int GetMin(int a, int b)
{
return (a <= b) ? a : b;
}
IoAddr *Process(int addrSize, int *detaSize, IoAddr *addr)
{
IoAddr *detatch = (IoAddr *)malloc(sizeof(IoAddr) * MAX_SIZE);
int secLength;
int upBound;
*detaSize = 0;
int min;
for (int i = 0; i < addrSize; ++i) {
secLength = (addr + i)->endAddr - (addr + i)->startAddr + 1;
while (secLength) {
upBound = GetUpBound(addr + i);
min = GetMin(upBound, secLength - 1);
detatch[*detaSize].startAddr = (addr + i)->startAddr;
detatch[*detaSize].endAddr = (addr + i)->startAddr + min;
++(*detaSize);
(addr + i)->startAddr += (min + 1);
if ((addr + i)->startAddr > (addr + i)->endAddr) {
break;
}
secLength = (addr + i)->endAddr - (addr + i)->startAddr + 1;
}
}
return detatch;
}
int main(void)
{
IoAddr *memory = (IoAddr *)malloc(sizeof(IoAddr) * 2);
memory[0].startAddr = 0;
memory[0].endAddr = 50;
memory[1].startAddr = 60;
memory[1].endAddr = 100;
int detaSize;
IoAddr *detatch = Process(2, &detaSize, memory);
printf("The allocation is as follows:\n\n");
for (int i = 0; i < detaSize; ++i) {
printf("[%-3d %-3d]\n", detatch[i].startAddr, detatch[i].endAddr);
}
free(memory);
free(detatch);
return 0;
}
3. 运行结果