I currently have a struct
typedef struct Entry {
int counter;
void *block;
} Entry;
and a mmap’ed block of memory
void *memPtr = mmap(NULL, someSize*1024, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
which I then add entries to the first part all the time (which is stupid, but that part’s a bit irrelevant) as such:
int AddEntry(void *data) {
Entry entry;
entry.counter = 1;
entry.block = malloc(sizeof(char *) * SECTOR_SIZE);
memcpy(entry.block, data, SECTOR_SIZE);
memcpy(&memPtr[0], &entry, sizeof(Entry));
return 0;
}
The problem here is that Entry is only 16 bytes long because block is a void pointer. What’s the best way to ensure that block is actually the size of sizeof(char *) * SECTOR_SIZE and actually has enough space for data, and how would one load data into entry.block?
Thanks!
If I’m reading the question correctly, you’re asking how to get a contiguous block of memory that can be accessed with a (smaller)
Entry *The most common way is to define your structure like:
typedef struct Entry { int counter; unsigned char block[1]; }Depending on the behavior of your compiler you can also define block to be a zero length array.
You can then malloc the space that you require for the structure and the SECTOR_SIZE:
int AddEntry(void *data) { Entry *entry; entry = malloc(sizeof(Entry) + ((SECTOR_SIZE-1) * sizeof(unsigned char)); // obligitory NULL checks assumed here// fill in structure
entry->counter = 1;
memcpy(entry->block, data, SECTOR_SIZE);
memcpy(&memPtr[0], &entry, sizeof(Entry) + ((SECTOR_SIZE-1) * sizeof(unsigned char));
return 0;
}
This will also allow you to access, say, the 78th byte of
blockby:entry->block[77]