clang warns that `ffi_type` is not compatible with `sizeof`

55 Views Asked by At

I am using libffi in C and receive a warning from clang-tidy that I do not quite understand.

I am allocating memory on the heap for an array of elements of type ffi_type:

ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type));

and receive the following warning:

Result of 'malloc' is converted to a pointer of type 'ffi_type *', which is incompatible with sizeof operand type 'ffi_type'

Could somebody give me a hint, how to fix it? The actual definition of the ffi_type is

typedef struct _ffi_type
{
  size_t size;
  unsigned short alignment;
  unsigned short type;
  struct _ffi_type **elements;
} ffi_type;

and actually it is not clear to me, why it is incompatible with the sizeof operator.

UPDATE: Helpful comments by @IanAbbot, @Toby Speight, @dbush helped me realized the (quite silly actually) issue. It must be

ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type *));

(mind the last asterisk), as the array is of elements of type ffi_type *.

1

There are 1 best solutions below

4
dbush On BEST ANSWER

You're allocating space for an array of type ffi_type, but assigning the result to a variable of type ffi_type ** which can hold an array of type ffi_type *. That's what you're being warned about.

Change the type of the sizeof expression to match the intended usage.

ffi_type **arg_types = malloc(num_total_args * sizeof(ffi_type *));

Or better yet (as it doesn't depend on the type of arg_types):

ffi_type **arg_types = malloc(num_total_args * sizeof *arg_types);