Linux中内存控制函数的使用


最近在学习Linux的C函数库,发现确实都很实用,要做嵌入式开发的人最好过一遍这个函数库,不要求很深入的理解,只要求看到这个函数引用时知道它是干什么的就可以了。这样,不管是你自己写代码开发Linux程序,还是看别人写的代码,都让你轻松很多。

在看内存控制函数的使用过程中,总结下了几个重要函数的使用方法和作用,比较简单,重在介绍,下面帖代码:

#include
#include
#include
#include
#include
#include
#include

struct test
{
int a[10];
char b[20];
}
main()
{
int fd;
void *start;
struct stat sb;
struct test *ptr = calloc(sizeof(struct test),10);          /*配置10个相邻的内存空间,内容初始化为0*/
if(ptr != NULL) printf("calloc successful\n");
void *p = malloc(1024);                                  /*配置1K内存*/
if(p != NULL) printf("malloc successful\n");
printf("Now I will free the memory space\n");
printf("page size = %d\n",getpagesize( ) );                     /*取得系统内存分页大小*/
free(ptr);                            /*释放分配的内存*/
free(p);
fd = open("/home/user/Linux-c/testfile",O_RDONLY);      /*打开文件/home/user/Linux-c/testfile*/
fstat(fd,&sb);                  /*取得文件大小*/
start = mmap(NULL,sb.st_size,PROT_READ,MAP_PRIVATE,fd,0);    /*将文件内容映射到内存中*/
if(start == MAP_FAILED)                 /*判断是否映射成功*/
   return;
printf("%s",start);
munmap(start,sb.st_size);                  /*解除映射*/
close(fd);
}

相关内容