Created
February 22, 2023 01:13
-
-
Save pavly-gerges/d83186b31d227353e5b90da1e25bd2ac to your computer and use it in GitHub Desktop.
Tests memory corruption due to partition memory overflow.
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) { | |
// Write C code here | |
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*) partition1.start_address) = 55; | |
*((int*) partition2.start_address) = 255; | |
*((long*) partition0.start_address) = 98236798234789478; | |
printf("%s\n", "ls part: Print partitions data: "); | |
printf("%lld\n", *((long*) partition0.start_address)); | |
printf("%i\n", *((int*) partition1.start_address)); | |
printf("%i\n", *((int*) partition2.start_address)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: