Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing if void * contains 0 numbytes?

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;
    }
like image 393
vindyz Avatar asked Dec 14 '22 11:12

vindyz


2 Answers

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;
}
like image 147
pm100 Avatar answered Dec 29 '22 00:12

pm100


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;
like image 37
R Sahu Avatar answered Dec 29 '22 00:12

R Sahu