您当前的位置: 首页 >  linux

qianbo_insist

暂无认证

  • 0浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

linux 内存管理

qianbo_insist 发布时间:2021-08-29 07:48:35 ,浏览量:0

c语言内存接口
#include 
void *malloc(size_t size);
数组和calloc

使用calloc 来申请固定大小内存的数据结构

    void *r;
    r = calloc(2,sizeof(struct tmap));
    if(!r)
    {
        perror("error of calloc");
        exit(EXIT_FAILURE);
    }

2 代表申请2 个tmap 空间,这里空间是连续的,否则就不是数组了,可以使用r[0] ,和r[1] 来使用空间。

调整内存数组大小
#include 
void *realloc(void *ptr, size_t size);

使用calloc 来申请固定大小内存的数据结构,然后用realloc 重新分配:

 void *p;
 p = calloc(1,sizeof(struct map));
 if(!p)
 {
     perror("error of xmalloc");
     exit(EXIT_FAILURE);
 }
 p = realloc(p,sizeof(struct tmap));

以下是样例和封装函数


#include 

typedef struct tmap
{
    int num;
    int a;
    char con[128];
    char x[2048];
}tmap;

void xmalloc(size_t size)
{
    void *p;
    p = malloc(size);
    if(!p)
    {
        perror("error of xmalloc");
        exit(EXIT_FAILURE);
    }
    return p;
}
void * xcalloc(size_t size)
{
    void *p;
    p = calloc(1,size);
    if(!p)
    {
        perror("error of xmalloc");
        exit(EXIT_FAILURE);
    }
    return p;
}

int main()
{
    printf("start...");
    char *p;
    p= malloc(2048);
    if(!p)
        perror("malloc error");
    free(p);
    tmap * map = malloc(sizeof(tmap));
    if(!map)
        perror("malloc map error");
    free(map);
    
    
    void *r;
    r = calloc(2,sizeof(struct tmap));
    if(!r)
    {
        perror("error of calloc");
        exit(EXIT_FAILURE);
    }
    r = realloc(r,sizeof(struct tmap));
    if(!r)
    {
        perror("error of realloc");
        exit(EXIT_FAILURE);
    }
    free(r);
    printf("over\n");
    
}

在vscode 下面执行得到结构 start...over start 和over 之间没有推出,表示成功

问题 1 重新分配大小

realloc 重新分配大小后,数据是否存在?标准c 的告诉我们,数据依然存在,不用手动进行拷贝工作,重新分配内存大小的意义在于两点:

1 缩减内存减少不必要的内存空间使用 2 加大内存以适应需要更多内存

那么问题依然存在,加大内存用量时,以前的数据还存在吗?答案是依然存在的,系统如果不能在以前的空间申请更大的内存,那么会查询连续内存,并且存在潜在的拷贝动作,这是要进行cpu消耗的,所以,如果使用内存池这种方式,尽量在开始时申请足够的内存,

#include 
#include 
typedef struct tmap
{
	int num;
	int a;
	char con[128];
	char x[2048];
}tmap;


int main()
{


	tmap *r, *s;
	r = calloc(2, sizeof(struct tmap));
	if (!r)
	{
		perror("error of calloc");
		exit(EXIT_FAILURE);
	}
	printf("r0 num is: %d\n", r[0].num);
	printf("r0 a is: %d\n", r[0].a);

	r[0].num = 100;
	r[0].a = 1000;
	s = realloc(r, sizeof(struct tmap));
	if (!s)
	{
		perror("error of realloc");
		free(r);
		exit(EXIT_FAILURE);
	}

	printf("s0 num is: %d\n", s[0].num);
	printf("s0 a is: %d\n", s[0].a);
	free(s);
	printf("over\n");

}

输出: 在这里插入图片描述 可见, 1 初始化时 ,calloc函数帮我们将内存清零 2 在重新分配内存后,数据并没有变化. 3 无论是没有复制内存还是已经复制了内存,对我们来说都是透明的。

2 内存对齐

32位系统时8字节对齐 64位系统16字节对齐 如果事先没有进行对齐,最好事先将字节对齐,以免自己在后面手动计算的情况下搞错地址。 大多数情况下,编译器和c库会自动处理对齐问题,三个函数,malloc 和 calloc 以及realloc 返回的内存空间都是对齐的。

3 大内存申请

请使用mmap 函数来进行磁盘和内存的映射

关于磁盘映射的文章

关注
打赏
1663161521
查看更多评论
立即登录/注册

微信扫码登录

0.6439s