I would like to write a generic function to detect if an array of pointers to some arbitrary type contains a NULL
. My initial attempt was something along these lines:
bool find_null (void *ptrs, size_t num_ptrs) {
void **array = ptrs;
size_t i;
for (i = 0; i < num_ptrs; ++i) {
if (array[i] == NULL) return true;
}
return false;
}
It was pointed out that this could cause a strict aliasing violation, since the array of pointers to Foo
would be accessed as array of pointers to void
, which is not listed as one of the allowed ways an object is allowed to be accessed in C.2011 §6.5¶7.
I could rewrite the function to access the array of pointers as unsigned char *
instead, but I am not sure how to perform the NULL
check without breaking strict aliasing. Can someone provide a valid technique?
bool find_null (void *ptrs, size_t num_ptrs) {
unsigned char *array = ptrs;
void *p;
size_t i;
for (i = 0; i < num_ptrs; ++i) {
memcpy(&p, array + i * sizeof(p), sizeof(p));
if (p == NULL) return true;
/*
* Above seems to still break strict aliasing.
* What should be done instead?
*/
}
return false;
}
The goal is to write a generic function that would work the same as a type specific function. In other words, a generic version of the function below:
bool find_null_Foo (Foo *array[], size_t num_ptrs) {
size_t i;
for (i = 0; i < num_ptrs; ++i) {
if (array[i] == NULL) return true;
}
return false;
}
sizeof(void*)
is equal tosizeof(Foo*)
. They can be unequal on non-byte-addressable machines, wheresizeof(void*)
is a little bit bigger thansizeof(Foo*)
due to the need to record the byte within the word that the pointer is referencing. – Lacto(void*)NULL
or want to handle the possibility that the platform has various null pointers values? (Of course all null pointers equate to each other - though they may have different encodings.) – Farmland