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;
}
In most cases, an empty element in an array of objects will contain null rather than a pointer to an actual object (by definition.) If there was a pointer to an object in any of the elements, the array isn't empty. So, iterate over the array and check whether each element == null.
int * pInt = NULL; To check for a null pointer before accessing any pointer variable.
The nullptr keyword can be used to test if a pointer or handle reference is null before the reference is used. Function calls among languages that use null pointer values for error checking should be interpreted correctly. You cannot initialize a handle to zero; only nullptr can be used.
Can I always reliably set a function pointer to NULL in C and C++? Yes, in any conforming C or C++ implementation this will work.
The generic function is not guaranteed to work as expected on systems where pointers to different types may have different representations and/or sizes. Thankfully such architectures are quite rare nowadays. Posix compliant systems for example are guaranteed to use the same representation and size for all pointer types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With