存储管理实验(一):内存管理

本文介绍了一种使用队列管理内存的方法,通过自定义队列结构和相关操作,实现了内存的有效分配、管理和回收。文章详细展示了如何创建队列、插入节点、获取节点并释放内存的过程,同时提供了观察Linux内存管理信息的命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

完成以下功能:以队列的方式管理内存,进行合理的内存分配、管理与回收。观察程序运行过程中进程所使用的内存变化。
使用两条命令观察 linux 中的内存管理信息:
$ cat /proc/meminfo
$ vmstat

#include <stdio.h>
typedef struct DataNode{
char *data;
struct DataNode *next;
} DataNode;
typedef struct{
DataNode *head, *tail;
} Que;
void queue_init(Que *myroot) {
myroot->head=NULL;
myroot->tail=NULL;
}
void queue_put(Que *myroot,DataNode
*myDataNode) {
if (myroot->tail!=NULL)
myroot->tail->next=myDataNode;
myroot->tail=myDataNode;
if (myroot->headNULL)
myroot->head=myDataNode;
}
DataNode *queue_get(Que *myroot) {
DataNode *myDataNode;
myDataNode=myroot->head;
if (myroot->head!=NULL)
{
myroot->head=myroot->head->next;
myDataNode->next=NULL;
if(myroot->head
NULL)
myroot->tail=NULL;
}
else
myDataNode=myroot->head;
return myDataNode;
}
main( ) {
Que *myroot;
DataNode *tmpNode;
char str[1024];
int ts,qs,i;
qs=sizeof(Que);
ts=sizeof(DataNode);
printf(“sizeof(Que):%d,sizeof(DataNo
de):%d\n”,qs,ts);
myroot=(Que *)malloc(qs);
queue_init(myroot);
for(i=0;i<4;i++)
{
scanf("%s",str);
tmpNode=(DataNode *)malloc(ts);
tmpNode->data=(char
*)malloc(strlen(str)+1);
strcpy(tmpNode->data,str);
tmpNode->next=NULL;
queue_put(myroot,tmpNode);
printf(“queue_put a node ,
used: %d\n”,strlen(str)+1+ts);
}
while(myroot->tail!=NULL)
{
tmpNode=queue_get(myroot);
printf(“queue_get a node: %s,
freed:%d\n”,tmpNode->data,s
trlen(tmpNode->data)+1+ts);
free(tmpNode->data);
free(tmpNode);
}
free(myroot);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值