I need generic way to check if void * contains 0 till num_bytes.
I came up with following approach. *p does not contain same type of data everytime hence cant do *(type*)p
bool is_pointer_0(void *p, int num) {
void *cmp;
cmp = (void*)malloc(num);
memset(cmp, 0, num);
if (memcmp(p, cmp, num)) {
free(cmp);
return false;
} else {
free(cmp);
return true;
}
}
The function allocates & frees up num bytes on every call, not pretty I think. Please suggest faster approaches. Appreciate the help.
Update :
How about this approach ?
bool is_pointer_0(void *p, int num) {
void *a = NULL;
memcpy(&a, p, num);
return a == NULL;
}
This code casts the void pointer to a char pointer. This allows the memory pointed at to be treated as a sequence of bytes. Then cycles through the specified length looking for non zero bytes. I do not know if the standards guarantee that this would work (ie casting a void* to a char* will provide a pointer to the raw bytes), but in real life it works
bool is_pointer_0(void *p, int num) {
char *c = (char *)p;
for(int i = 0; i < num; i++)
if(c[i]) return false;
return true;
}
You can cast the pointer to a char*
or unsigned char*
and check the values of the elements.
unsigned char* cp = reinterpret_cast<unsigned char*>(p);
for (int i = 0; i < num; ++i )
{
if ( cp[i] != 0 )
{
return false;
}
}
return true;
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