FFmpeg源码:av_strlcpy函数分析
一、引言
在C/C++编程中经常会用到strcpy这个字符串复制函数。strcpy是C/C++中的一个标准函数,可以把含有'\0'结束符的字符串复制到另一个地址空间。但是strcpy不会检查目标数组dst的大小是否足以容纳源字符串src,如果目标数组太小,将会导致缓冲区溢出。针对该问题很多C/C++开源库都会选择自己实现strcpy函数来保证安全性。而FFmpeg自定义了av_strlcpy函数,在实现strcpy函数功能的同时保证不会造成缓冲区溢出。
二、av_strlcpy函数的声明
av_strlcpy函数声明在FFmpeg源码(本文演示用的FFmpeg源码版本为7.0.1)的头文件libavutil/avstring.h中:
/**
* Copy the string src to dst, but no more than size - 1 bytes, and
* null-terminate dst.
*
* This function is the same as BSD strlcpy().
*
* @param dst destination buffer
* @param src source string
* @param size size of destination buffer
* @return the length of src
*
* @warning since the return value is the length of src, src absolutely
* _must_ be a properly 0-terminated string, otherwise this will read beyond
* the end of the buffer and possibly crash.
*/
size_t av_strlcpy(char *dst, const char *src, size_t size);
该函数的作用是:在已知dst缓冲区大小并不会造成缓冲区溢出前提下,将src地址开始的字符串复制到以dst开始的地址空间。
形参dst:输出型参数,目的字符串开始的指针(即目标缓冲区)。
形参src:输入型参数,源字符串的开始地址。
形参size:输入型参数,dst缓冲区的大小。
返回值:src字符串的大小。
三、av_strlcpy函数的定义
av_strlcpy函数定义在libavutil/avstring.c中:
size_t av_strlcpy(char *dst, const char *src, size_t size)
{
size_t len = 0;
while (++len < size && *src)
*dst++ = *src++;
if (len <= size)
*dst = 0;
return len + strlen(src) - 1;
}
四、参考
《百度百科——strlcpy》