Last active
February 21, 2023 23:02
-
-
Save pavly-gerges/3e9910c76005ee418322efabb6a9c276 to your computer and use it in GitHub Desktop.
A simple example to a buffer partitioning scheme
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
typedef struct { | |
void* start_address; | |
void* end_address; | |
size_t offset; | |
size_t size; | |
size_t pointer_location; | |
void (*invalidate)(void*); | |
} MemoryPartition; | |
static inline void invalidate(MemoryPartition* partition) { | |
partition->start_address += partition->offset; | |
partition->end_address = partition->start_address + partition->size; | |
partition->pointer_location = partition->offset + partition->size; | |
} | |
static inline MemoryPartition create(void* buffer, size_t offset, size_t size) { | |
MemoryPartition partition = { | |
buffer + offset, | |
(buffer + offset) + size, | |
offset, | |
size, | |
offset + size, | |
&invalidate | |
}; | |
return partition; | |
} | |
int main() { | |
const size_t size = 4; | |
void* buffer = (void*) malloc(size * 3); | |
printf("Allocated buffer start address = %p\n", buffer); | |
const MemoryPartition partition0 = create(buffer, 0, size); | |
printf("Partition0 start address = %p\n", partition0.start_address); | |
printf("Partition0 end address = %p\n", partition0.end_address); | |
const MemoryPartition partition1 = create(buffer, partition0.pointer_location + 1, size); | |
printf("Partition1 start address = %p\n", partition1.start_address); | |
printf("Partition1 end address = %p\n", partition1.end_address); | |
const MemoryPartition partition2 = create(buffer, partition1.pointer_location + 1, size); | |
printf("Partition2 start address = %p\n", partition2.start_address); | |
printf("Partition2 end address = %p\n", partition2.end_address); | |
/* add some data to the partitions */ | |
*((int*) partition0.start_address) = 44; | |
*((int*) partition1.start_address) = 55; | |
*((int*) partition2.start_address) = 255; | |
printf("%s\n", "ls part: Print partitions data: "); | |
printf("%i\n", *((int*) partition0.start_address)); | |
printf("%i\n", *((int*) partition1.start_address)); | |
printf("%i\n", *((int*) partition2.start_address)); | |
return 0; | |
} |
Author
pavly-gerges
commented
Feb 21, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment