avoid type safety violations when calling 'bsearch', 'qsort'
GCC 14 contains some breaking changes, the notice for which suggests it is going to become more strict about dealing with function pointer type casting/coercion:¹
Type checking on pointer types (
-Werror=incompatible-pointer-types
)
…
A frequent source of incompatible function pointer types involves callback functions that have more specific argument types (or less specific return types) than the function pointer they are assigned to. For example, old code which attempts to sort an array of strings might look like this:#include <stddef.h> #include <stdlib.h> #include <string.h> int compare (char **a, char **b) { return strcmp (*a, *b); } void sort (char **array, size_t length) { qsort (array, length, sizeof (*array), compare); }
To address this, the callback function should be defined with the correct type, and the arguments should be cast as appropriate before they are used (as calling a function through a function pointer of an incorrect type is undefined):
int compare (const void *a1, const void *b1) { char *const *a = a1; char *const *b = b1; return strcmp (*a, *b); }
This change applies GCC’s suggested phrasing to usage of bsearch
and qsort
. There are also some other minor change commits included.