#if AV_GCC_VERSION_AT_LEAST(4,3)
#define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__)))
#else
#define av_alloc_size(...)
#endif
/**
* Allocate a memory block for an array with av_mallocz().
*
* The allocated memory will have size `size * nmemb` bytes.
*
* @param nmemb Number of elements
* @param size Size of the single element
* @return Pointer to the allocated block, or `NULL` if the block cannot
* be allocated
*
* @see av_mallocz()
* @see av_malloc_array()
*/
av_alloc_size(1, 2) static inline void *av_mallocz_array(size_t nmemb,
size_t size)
{
if (!size || nmemb >= INT_MAX / size)
return NULL;
return av_mallocz(nmemb * size);
}
我是c lang primer。看开源的时候看到这个功能。但它是什么样的功能呢?我以前从未见过这种功能。 av_alloc_size(1, 2)
和*av_mallocz_array
有什么关系?
最佳答案
它只是一个扩展为 GCC 特定属性 (__attribute__((alloc_size()))
) 的宏,进一步“描述”该函数。来自GCC documentation :
alloc_size
The alloc_size attribute is used to tell the compiler that the function return value points to memory, where the size is given by one or two of the functions parameters. GCC uses this information to improve the correctness of
__builtin_object_size
.The function parameter(s) denoting the allocated size are specified by one or two integer arguments supplied to the attribute. The allocated size is either the value of the single function argument specified or the product of the two function arguments specified. Argument numbering starts at one.
For instance,
void* my_calloc(size_t, size_t) __attribute__((alloc_size(1,2))) void* my_realloc(void*, size_t) __attribute__((alloc_size(2)))
declares that
my_calloc
returns memory of the size given by the product of parameter 1 and 2 and thatmy_realloc
returns memory of the size given by parameter 2.
因此,简而言之,它通过让编译器知道该函数执行动态内存分配来帮助编译器更好地“理解”代码,例如标准函数 malloc()
和 calloc ()
。如果没有它,代码当然也可以工作。
这些行:
#if AV_GCC_VERSION_AT_LEAST(4,3)
#define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__)))
#else
#define av_alloc_size(...)
#endif
确保扩展仅在使用 GCC 4.3 或更高版本编译时发生。在所有其他情况下,第二个 #define
只会使 av_alloc_size()
扩展为空字符串(空字符串)。
关于c - 嵌套c语言函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44879476/