clang-tidy报ffi_type与sizeof不兼容,malloc分配内存问题如何解决?
C语言使用libffi库时clang-tidy警告问题及修复
问题场景
在C语言中使用libffi库时,尝试在堆上为ffi_type指针类型的数组分配内存,编写代码如下:
ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type));
随后收到clang-tidy的警告,无法理解其原因。
警告内容
Result of 'malloc' is converted to a pointer of type 'ffi_type *', which is incompatible with sizeof operand type 'ffi_type'
ffi_type类型定义
typedef struct _ffi_type { size_t size; unsigned short alignment; unsigned short type; struct _ffi_type **elements; } ffi_type;
问题原因与修复
问题分析
代码中arg_types是ffi_type **类型,指向的是**ffi_type *类型元素的数组**,但malloc计算内存时用了sizeof(ffi_type)——这是单个ffi_type结构体的大小,而非ffi_type指针的大小,两者类型不匹配,因此触发clang-tidy警告。
修复后的代码
正确写法需计算ffi_type *的大小:
ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type *));
更新说明
感谢@IanAbbot、@Toby Speight、@dbush的评论,已明确问题核心:数组元素类型是ffi_type *,所以sizeof的操作数要对应指针类型。
内容的提问来源于stack exchange,提问作者Dmitry Kabanov
相关产品推荐
相关产品推荐

