I'm trying to model a basic CPU by mmapping a 1 MiB file, corresponding to the RAM size. I want to read/write this file. My confusion is that I thought I could just mmap my file, and then index into the memory chunk as if it were an array. I've seen a few examples online that have done as much. For example, given the snippet below:
int16_t ramD;
if ( (ramD = open("ramMap.txt", O_RDWR | O_CREAT, 1)) == -1)
{
errx(EX_OSERR, "RAM could not be initialized");
}
uint16_t* ram = mmap(0, ram_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, ramD, 0);
How would I access specific locations within this mmapped file for reading and writing? I thought it would be as simple as something like ram[36]
which would give me access to the 36th byte offset from the pointer returned by mmap, but this doesn't seem to be the case. To test I did a printf("%p\n", (void *) &ram);
to see what address mmap was pointing to which gave me 0x7fffffffde18
, (which, by the way, is nowhere close to my specified mmap parameter 0). Meanwhile, printf("%p\n", (void *) &ram[36])
returns 0x7ffff7ee1048
.
Is mmap not giving me memory in a linear chunk? What am I missing here?
This
printf("%p\n", (void *) &ram);
gives you the address of your local variable ram
on the stack. You want
printf("%p\n", (void *)ram);
to get the address of the ram you mmapped. Also, since you declared ram
as a uint16_t
, ram[36]
will be the 36th1 16-bit word of the memory (bytes 72 and 73).
1Counting from 0 of course