⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 memmgr_linux.c

📁 模拟内存管理。 申请内存时
💻 C
字号:
/* 
 * 内存管理实验程序残缺版 1.2.2
 * 把一个数组模拟为内存,然后针对该块内存实现内存的分配和回收算法
 * 作者:Sunner Sun
 * 最后修改时间:2005-3-25 16:53
 */

#include <stdio.h>

#define MEM_SIZE 80
char memory[MEM_SIZE];

void* GetBlock(unsigned int size);
int FreeBlock(void* pBlock);
int IsFree(int unit);

/* 在数组memory的分配size大小的内存块,把首地址返回。
   如果分配失败,返回NULL */
void* GetBlock(unsigned int size)
{
	return memory;
}

/* 释放首地址为pBlock的内存块。
   成功返回非0值,失败返回0 */
int FreeBlock(void* pBlock)
{
	return !0;
}

/* 判断数组memory中下标为unit的单元是否被占用。
   空闲返回非0,否则返回0 */
int IsFree(int unit)
{
	return !0;
}


/************************************************
 * 下面为测试代码,不需要修改,也不许使用其定义 *
 * 的各种变量、宏、结构等                       *
 ************************************************/

#define MAX_BLOCK_SIZE	10
#define BLOCK_COUNT		80
struct BLOCK
{
	void* p;
	int size;
};

void PrintMemoryUsage(void);
int New(struct BLOCK *pBlocks);
int Delete(struct BLOCK *pBlocks);

int main(void)
{
	struct BLOCK blocks[BLOCK_COUNT] = {0,0};

	int ch = 0;
	int rtn = 1;
	int i;
	
	do
	{
		switch (ch)
		{
		case 'n':
			rtn = New(blocks);
			break;
		case 'd':
			rtn = Delete(blocks);
			break;
		case '\n':
			continue;
			break;
		}
		if (!rtn)
			printf("\nError!!!!\n");
		PrintMemoryUsage();
		printf("Input \'n\' to new, \'d\' to delete and \'q\' to quit:");

	} while ((ch=getchar()) != 'q');

	/* 删除所有已申请的block */
	for (i=0; i<BLOCK_COUNT; i++)
	{
		if (blocks[i].p != NULL)
		{
			FreeBlock(blocks[i].p);
		}
	}
	
	return 0;
}

/* 打印memory分配情况 */
void PrintMemoryUsage(void)
{
	int i;

	putchar('\n');
	
	for (i=0; i<MEM_SIZE; i++)
	{
		if (i%10 == 0)
			putchar('|');
		else
			putchar(' ');
	}
	
	putchar('\n');

	for (i=0; i<MEM_SIZE; i++)
	{
		if (IsFree(i))
			putchar('-');
		else
			putchar('*');
	}

	putchar('\n');
}

/* 新申请block */
int New(struct BLOCK *pBlocks)
{
	int size = 0;

	while (size < 1 || size > MAX_BLOCK_SIZE)
	{
		printf("Size?[1-%d]", MAX_BLOCK_SIZE);
		scanf("%d", &size);
	}

	while (pBlocks->p != NULL)
		pBlocks++;

	pBlocks->p = GetBlock(size);
	pBlocks->size = size;

	return (pBlocks->p != NULL);
}

/* 删除已经申请的block */
int Delete(struct BLOCK *pBlocks)
{
	int i;

	for (i=0; i<BLOCK_COUNT; i++)
	{
		if (pBlocks[i].p != NULL)
		{
			printf("%d:%d\t", i, pBlocks[i].size);
		}
	}
	printf("\nWhich to delete:");
	scanf("%d", &i);
	if (FreeBlock(pBlocks[i].p))
	{
		pBlocks[i].p = NULL;
		return !0;
	}
	else
		return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -