clang 警告 `ffi_type` 与 `sizeof` 不兼容

Dmi*_*nov 2 c clang-tidy

libffi在 C 中使用并收到一条警告,clang-tidy说我不太明白。

我在堆上为类型的元素数组分配内存ffi_type

ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type));
Run Code Online (Sandbox Code Playgroud)

并收到以下警告:

Result of 'malloc' is converted to a pointer of type 'ffi_type *', which is incompatible with sizeof operand type 'ffi_type'
Run Code Online (Sandbox Code Playgroud)

有人可以给我提示,如何修复它吗?的实际定义ffi_type

ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type));
Run Code Online (Sandbox Code Playgroud)

实际上我不清楚为什么它与 sizeof 运算符不兼容。

更新:@IanAbbot、@Toby Speight、@dbush 的有用评论帮助我意识到了这个(实际上很愚蠢)问题。一定是

ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type *));
Run Code Online (Sandbox Code Playgroud)

(注意最后一个星号),因为数组的元素类型为ffi_type *

dbu*_*ush 5

您正在为 类型的数组分配空间ffi_type,但将结果分配给ffi_type **可以保存类型 的数组的类型的变量ffi_type *。这就是你被警告的原因。

更改表达式的类型sizeof以匹配预期用途。

ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type *));
Run Code Online (Sandbox Code Playgroud)

或者更好(因为它不依赖于 的类型arg_types):

ffi_type **arg_types = malloc(num_total_args * sizeof *arg_types);
Run Code Online (Sandbox Code Playgroud)