Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know where the segment of memory is all Zero

I mean, I malloc a segment of memory, maybe 1k maybe 20bytes.. assume the pointer is pMem How can I know the content pMem refered is all Zero or \0 . I know memcmp but the second parameter should another memory address... thanx

like image 411
Shaobo Wang Avatar asked Nov 27 '22 20:11

Shaobo Wang


1 Answers

As others have already suggested you probably want memset or calloc.

But if you actually do want to check if a memory area is all zero, you can compare it with itself but shifted by one.

bool allZero = pMem[0] == '\0' && !memcmp(pMem, pMem + 1, length - 1);

where length is the number of bytes you want to be zero.

like image 63
Mark Byers Avatar answered Nov 29 '22 10:11

Mark Byers