目录

南邮-操作系统实验三存储管理

南邮 | 操作系统实验三:存储管理

  1. 理解操作系统存储管理原理。
  2. 研读Linux 内存管理所用到的文件include/linux/mm.h,主要包括两个数据结构:mem_map、free_area。
  3. 在Linux 下,用malloc()函数实现cat或copy命令。

例程1

申请内存、使用内存以及释放一块内存

#include <stdio.h> 
#include <stdlib.h>  //exit函数,实验指导上少了这一个头文件
#include <string.h> 
#include <malloc.h> 
int main(void) 
{ 
char * str; 
if ((str=(char*)malloc(10))==NULL) 
{ 
  printf("not enough memory to allocate buffer\\n"); 
  exit(1); 
} 
strcpy(str,"hello"); 
printf("string is %s\\n",str); 
free(str); 
return 0; 
}

例程2

在打开文件后,通过fstat()获得文件长度,然后通过malloc()系统调用申请响应大小的内存空间,通过read()将文件内容完全读入该内存空间,并显示出来。

#include<stdio.h> 
#include <sys/stat.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <malloc.h> 
#include <string.h>  //实验指导上少了这一个头文件
#include <sys/types.h>  //实验指导上少了这一个头文件
#include <fcntl.h>  //实验指导上少了这一个头文件
main() 
{ 
  int fd,len; 
  void *tp; 
  struct stat ps; 
  //fd=open(“/home/jf03/try”,0); 
 fd = open(/home/wonz/b16xxxxxx.c, 0);  //实验指导上这里写错了
  fstat(fd,&ps); 
  len=ps.st_size; 
  tp=malloc(len); 
  read(fd,tp,len); 
  //printf(“%s\\n”,tp); 
printf(%s\n,tp);  //实验指导上这里写错了
printf(the length of the file: %d\n, len);  //实验指导上这里写错了
  close(fd); 
}