咸寧網(wǎng)站設(shè)計自制網(wǎng)頁
一、引言
在C/C++編程中經(jīng)常會用到strcpy這個字符串復制函數(shù)。strcpy是C/C++中的一個標準函數(shù),可以把含有'\0'結(jié)束符的字符串復制到另一個地址空間。但是strcpy不會檢查目標數(shù)組dst的大小是否足以容納源字符串src,如果目標數(shù)組太小,將會導致緩沖區(qū)溢出。針對該問題很多C/C++開源庫都會選擇自己實現(xiàn)strcpy函數(shù)來保證安全性。而FFmpeg自定義了av_strlcpy函數(shù),在實現(xiàn)strcpy函數(shù)功能的同時保證不會造成緩沖區(qū)溢出。
二、av_strlcpy函數(shù)的聲明
av_strlcpy函數(shù)聲明在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);
該函數(shù)的作用是:在已知dst緩沖區(qū)大小并不會造成緩沖區(qū)溢出前提下,將src地址開始的字符串復制到以dst開始的地址空間。
形參dst:輸出型參數(shù),目的字符串開始的指針(即目標緩沖區(qū))。
形參src:輸入型參數(shù),源字符串的開始地址。
形參size:輸入型參數(shù),dst緩沖區(qū)的大小。
返回值:src字符串的大小。
三、av_strlcpy函數(shù)的定義
av_strlcpy函數(shù)定義在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》