Rio
Rio

Reputation: 14892

Understanding the mmap size parameter

I'm having a hard time understanding the size parameter of mmap (sorry my C is rusty). For example (taken from another SO post)

If we have:

typedef struct container {
    int counter;
} container;

container *memory;
memory = mmap(NULL, 500*sizeof(container), PROT_READ|PROT_WRITE, MAP_SHARED, -1, 0);

container *entry = (container *) malloc(sizeof(container));
entry->counter = 1;
// Just arbitrarily
memory[1] = *entry;

Won't memory[1] simply be a pointer to a container and therefore not be the sizeof(container)? Or is there method to use mmap that indeed will ensure that only 500 entries of container can be inserted? Or should memory be accessed in steps of sizeof(container)?

Thanks!

Upvotes: 1

Views: 2535

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215387

First of all, while you're using mmap to obtain the memory, nothing in your question is specific to mmap. The same conclusions would apply if you were just doing:

container *memory = malloc(500*sizeof(container));

In either case, you have a block of memory of length 500*sizeof(container) bytes, and the pointer returned can be considered as pointing to the first element of an array of 500 container structures.

Upvotes: 2

Related Questions