FFMPEG4.1源码分析之 内存管理APIs av_realloc()

1 av_realloc()


av_realloc() 声明:

  • 所属库:libavutil(lavu),该库是ffmpeg的功能库,当前函数属于内存管理功能
  • 头文件:libavutil/mem.h
  • 功能:1.  分配空间 / 重新分配空间(已分配空间的伸缩) / 释放一块内存。
                    1)ptr为NULL,且size>0时,分配一块新的内存块;
                    2)ptr不为空,size=0时,释放ptr指向的内存空间;
                    3)  ptr不为空,size>0时,扩展ptr指向的内存空间;
                    4)ptr不为空,size<0时,收缩ptr指向的内存块空间;
               2.  注意一点就是av_malloc()保证内存对齐,而本函数不保证内存对齐
/**
 * Allocate, reallocate, or free a block of memory.
 *
 * If `ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is
 * zero, free the memory block pointed to by `ptr`. Otherwise, expand or
 * shrink that block of memory according to `size`.
 *
 * @param ptr  Pointer to a memory block already allocated with
 *             av_realloc() or `NULL`
 * @param size Size in bytes of the memory block to be allocated or
 *             reallocated
 *
 * @return Pointer to a newly-reallocated block or `NULL` if the block
 *         cannot be reallocated or the function is used to free the memory block
 *
 * @warning Unlike av_malloc(), the returned pointer is not guaranteed to be
 *          correctly aligned.
 * @see av_fast_realloc()
 * @see av_reallocp()
 */
void *av_realloc(void *ptr, size_t size) av_alloc_size(2);

av_realloc()  源码: 

  • 源文件:mem.c
void *av_realloc(void *ptr, size_t size)
{
    /* let's disallow possibly ambiguous cases */
    if (size > (max_alloc_size - 32))
        return NULL;

#if HAVE_ALIGNED_MALLOC
    return _aligned_realloc(ptr, size + !size, ALIGN);
#else
    return realloc(ptr, size + !size);
#endif
}
  1.  av_realloc() 实现利用的是c库realloc()和_aligned_realloc(),其中realloc()函数详解见 https://www.runoob.com/cprogramming/c-function-realloc.html
  2. 关于av_realloc()的两个疑问点:
     2.1)第一个是对入参size的合法性验证方面,为啥分配的size必须比max_alloc_size小32.
     2.2)关于size=0,那么会释放ptr指针指向的内存这点。源码上对于size的处理:size+!size这点确保了传递给c库的realloc()和_aligned_realloc()不可能为0,而是为1。那么,按照realloc()的解释,只是将ptr指向的内存收缩为1个字节而已,而非释放了全部空间。是否是理解错误,这儿存疑。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值