#include <stdio.h> #include <stdint.h> #define BLOCK_SIZE 16 #define POOL_SIZE 64 uint8_t pool[POOL_SIZE * BLOCK_SIZE]; uint8_t free_list[POOL_SIZE]; int free_count = 0; void mempool_init() { for (int i = 0; i < POOL_SIZE; i++) { free_list[i] = 1; // mark all blocks free } free_count = POOL_SIZE; } int main() { mempool_init(); printf("Free blocks: %d\n", free_count); return 0; }
#include <stdio.h> #include <stdint.h> #define BLOCK_SIZE 8 #define POOL_SIZE 4 uint8_t pool[POOL_SIZE * BLOCK_SIZE]; uint8_t free_list[POOL_SIZE]; int free_count = 0; void mempool_init() { for (int i = 0; i < POOL_SIZE; i++) { free_list[i] = 1; } free_count = POOL_SIZE; } void* mempool_alloc() { for (int i = 0; i < POOL_SIZE; i++) { if (free_list[i]) { free_list[i] = 0; free_count--; return &pool[i * BLOCK_SIZE]; } } return NULL; } int main() { mempool_init(); mempool_alloc(); mempool_alloc(); printf("Free blocks: %d\n", free_count); return 0; }
#include <stdio.h> #include <stdint.h> #define BLOCK_SIZE 8 #define POOL_SIZE 2 uint8_t pool[POOL_SIZE * BLOCK_SIZE]; uint8_t free_list[POOL_SIZE]; int free_count = 0; void mempool_init() { for (int i = 0; i < POOL_SIZE; i++) { free_list[i] = 1; } free_count = POOL_SIZE; } void* mempool_alloc() { for (int i = 0; i < POOL_SIZE; i++) { if (free_list[i]) { free_list[i] = 0; free_count--; return &pool[i * BLOCK_SIZE]; } } return NULL; } void mempool_free(void* ptr) { int index = ((uint8_t*)ptr - pool) / BLOCK_SIZE; free_list[index] = 1; free_count++; } int main() { mempool_init(); void* p = mempool_alloc(); mempool_free(p); mempool_free(p); // double free printf("Free blocks: %d\n", free_count); return 0; }
void* mempool_alloc() {
for (int i = 0; i < POOL_SIZE; i++) {
if (free_list[i]) {
free_list[i] = 0;
free_count--;
return &pool[i * BLOCK_SIZE];
}
}
return NULL;
}#define POOL_SIZE 10 // Initially all blocks free // Allocate 4 blocks // Free 2 blocks // Allocate 3 blocks // How many free blocks remain?
