My code looks like:
#include <assert.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
int main()
{
char *mm;
int mem_size = 1 << 30;
long *ptr, *end;
mm = (char *) mmap(NULL, mem_size, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, -1, 0);
assert(mm != MAP_FAILED);
memset(mm, 0xff, mem_size);
end = (long *) mm + mem_size;
for(ptr = (long *) mm ; ptr < end ; ptr++){
if((*ptr) != ~(long)0){
printf("At %p found 0x%" PRIx64 "\n", ptr, *ptr);
exit(1);
}
}
exit(0);
}
I set all my memory to 0xff to fill it with ones. I would expect that the print never executes but it is not so. When I search for a memory region that contains a bit set to zero I find an address into the memory region. Where is the error?
end = (long *) mm + mem_size;" why do you castmmtolong*? yourendwill be way beyond the memory yoummap()ed.(long *) mm + mem_sizewill point to something way beyond the end of memory, because mem_size will be multiplied by the size of long before the addition. You probably mean(long *)(mm + memsize).PRIx64is foruint64_t, yet you're using long