Comparison if void * contains 0 numbytes?

I need a general way to check if void * 0 contains up to num_bytes. I came up with the following approach. * p does not contain the same data type every time, therefore can not 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 and frees num bytes on every call, but not really 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;
    }
+4
source share
5 answers

void char. , . , . , , (, void * char * ),

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;
}
+8

char* unsigned char* .

unsigned char* cp = reinterpret_cast<unsigned char*>(p);
for (int i = 0; i < num; ++i )
{
   if ( cp[i] != 0 )
   {
      return false;
   }
}
return true;
+4

. . - .

, , memcmp(): .

int memcmp0(const void *buf, size_t n) {
  #define TESTVALUE 0
  const char *cbuf = (const char *) buf;
  while (n > 0) {

    // If odd size, last byte not 0?
    if (n % 2 && (cbuf[n - 1] != TESTVALUE)) return 0;

    // 1st half matches 2nd half?
    size_t half = n / 2;
    if(memcmp(cbuf, &cbuf[half], half) != 0) return 0;

    n = half;
  }
  return 1;
}

, 0, TESTVALUE.

: log2(n) .

+1

:

, , memcmp(): .

Check the first value, then use memcmp()for comparison ptr[0],ptr[1], then ptr[1],ptr[2], then ptr[2],ptr[3], etc.

int memcmpfast(const void *ptr, size_t n, char testvalue) {
  const char *cptr = (const char *) ptr;
  if (n == 0) return 1;
  if (cptr[0] != testvalue) return 0;
  return memcmp(cptr, cptr + 1, n - 1) == 0;
}
0
source

I would probably say something like this:

bool is_pointer_0(void* p, int num)
{
    return std::search_n((char*)p, (char*)p + num, num, 0) == p;
}

Or that:

bool is_pointer_0(void* p, int num)
{
    return std::all_of((char*)p, (char*)p + num, [](char c){return c == 0;});
}
-1
source

Source: https://habr.com/ru/post/1607880/


All Articles