apue存储空间分配

存储空间分配

  1. malloc,分配指定字节的存储区,未进行初始化

  2. calloc,为指定长度的对象分配存储空间,每一bit初始化为0

  3. realloc,增加或减少之前分配的长度,新增区域未进行初始化

函数
#include <stdlib.h>

void *
calloc(size_t count, size_t size);

void *
malloc(size_t size);

void *
realloc(void *ptr, size_t size);

void
free(void *ptr);

函数说明
函数参数返回值
alloccount:分配类型对数量,size:每个类型字节数成功返回空间地址,失败返回NULL
mallocsize:表示分配字节个数成功返回空间地址,失败返回NULL
reallocptr:当前需要修改的空间,size:修改后的空间大小成功返回空间地址,失败返回NULL
freeptr:需要释放的空间无返回值

man手册说明:

The malloc() function allocates size bytes of memory and returns a
pointer to the allocated memory.

The calloc() function contiguously allocates enough space for count
objects that are size bytes of memory each and returns a pointer to the
allocated memory.  The allocated memory is filled with bytes of value
zero

The realloc() function tries to change the size of the allocation pointed
to by ptr to size, and returns ptr.  If there is not enough room to
enlarge the memory allocation pointed to by ptr, realloc() creates a new
allocation, copies as much of the old data pointed to by ptr as will fit
to the new allocation, frees the old allocation, and returns a pointer to
the allocated memory.  If ptr is NULL, realloc() is identical to a call
to malloc() for size bytes.  If size is zero and ptr is not NULL, a new,
minimum sized object is allocated and the original object is freed.  When
extending a region allocated with calloc(3), realloc(3) does not guaran-
tee that the additional memory is also zero-filled.

The free() function deallocates the memory allocation pointed to by ptr.
If ptr is a NULL pointer, no operation is performed.

注意事项

realloc 参数size为期望的ptr指向空间的大小,当size大于ptr原有长度,可能会导致重新开辟完整空间,更改ptr的地址

泄漏:调用alloc类函数后,最终未调用free释放空间。对同一空间调用两次free

测试程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NSIZE 10

int main(){
    char *ptr = NULL;
    int i;
    if((ptr = malloc((NSIZE) * sizeof(char))) == NULL)
        return -1;
    memset(ptr,0,NSIZE * sizeof(char));
    for(i = 0; i < NSIZE-1; i++)
        ptr[i] = 'A' + i;
    ptr[i] = '\0';
    printf("ptr is %s\n",ptr);
    //记得最后释放,并将ptr置空
    free(ptr);
    ptr = NULL;
    return 0;
}

替代存储空间分配程序(暂时不关注)

  1. libmalloc
  2. vmalloc
  3. quick-fit
  4. jemalloc
  5. TCMalloc 用于替代malloc族函数,提高性能,扩展性,存储效率
    内置堆检查程序
  6. 函数alloca 在栈上分配空间,不必为释放内存费心。增加了栈对长度,在某些系统不支持

本内容为个人学习内容,如有不正请指正,与诸君共勉
学习unp第一天

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值