完成以下功能:以队列的方式管理内存,进行合理的内存分配、管理与回收。观察程序运行过程中进程所使用的内存变化。
使用两条命令观察 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->headNULL)
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);
}