1

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?

4
  • Describe where in the memory you get the error. Is it near the beginning, near the end? Is it always at the same place relative to the end of memory? Commented Oct 15, 2018 at 19:47
  • 3
    "end = (long *) mm + mem_size;" why do you cast mm to long*? your end will be way beyond the memory you mmap()ed. Commented Oct 15, 2018 at 19:50
  • 1
    Note: (long *) mm + mem_size will 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). Commented Oct 15, 2018 at 19:51
  • 2
    btw PRIx64 is for uint64_t, yet you're using long Commented Oct 15, 2018 at 20:22

1 Answer 1

7

You're scanning way past the end of the mapped memory.

end = (long *) mm + mem_size;

You convert mm to a long*. Adding mem_size to that pointer value advances the pointer by mem_size * sizeof (long) bytes.

Change that to:

end = (long *)(mm + mem_size);
Sign up to request clarification or add additional context in comments.

2 Comments

@EmanueleVannacci: Precedence errors like this can be subtle and hard to catch; count yourself lucky that you only wasted a single day. When in doubt, use parentheses.
Another option is to declare long *mm and then use &mm[mem_size]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.