#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MEMORY_SIZE 1024 // Tamaño total de la memoria
#define BLOCK_SIZE 128 // Tamaño de cada bloque
typedef struct Block {
bool isFree; // Indica si el bloque está libre
size_t size; // Tamaño del bloque
struct Block* next; // Puntero al siguiente bloque
} Block;
Block memory[MEMORY_SIZE / BLOCK_SIZE]; // Simulación de memoria
void initializeMemory() {
for (int i = 0; i < MEMORY_SIZE / BLOCK_SIZE; i++) {
memory[i].isFree = true; // Todos los bloques están libres al inicio
memory[i].size = BLOCK_SIZE;
memory[i].next = (i < (MEMORY_SIZE / BLOCK_SIZE) - 1) ? &memory[i + 1] : NULL;
}
}
void* allocateMemory(size_t size) {
for (int i = 0; i < MEMORY_SIZE / BLOCK_SIZE; i++) {
if (memory[i].isFree && memory[i].size >= size) {
memory[i].isFree = false; // Marcar el bloque como ocupado
return (void*)&memory[i]; // Retornar la dirección del bloque
}
}
return NULL; // No hay suficiente memoria
}
void freeMemory(void* ptr) {
Block* block = (Block*)ptr;
block->isFree = true; // Marcar el bloque como libre
}
void printMemoryStatus() {
for (int i = 0; i < MEMORY_SIZE / BLOCK_SIZE; i++) {
printf("Block %d: %s\n", i, memory[i].isFree ? "Free" : "Occupied");
}
}
int main() {
initializeMemory();
printMemoryStatus();
// Simulación de asignación de memoria
void* ptr1 = allocateMemory(128);
printf("\nAllocated 128 bytes.\n");
printMemoryStatus();
void* ptr2 = allocateMemory(64);
printf("\nAllocated 64 bytes.\n");
printMemoryStatus();
// Liberar memoria
freeMemory(ptr1);
printf("\nFreed 128 bytes.\n");
printMemoryStatus();
return 0;
}