Skip to content

Commit

Permalink
[memory] First step towards a new FlushableMemory type
Browse files Browse the repository at this point in the history
  • Loading branch information
thoni56 committed Jan 21, 2025
1 parent cd176e8 commit 18b05aa
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/memory.c
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,21 @@ bool cxMemoryIsFreed(void *pointer) {
void cxFreeUntil(void *pointer) {
memoryFreeUntil(&cxMemory, pointer);
}

/***********************************************************************/
/* New FlushableMemory */

void initFlushableMemory(FlushableMemory *memory) {
memory->size = 0;
memory->top = 0;
memory->blocks = NULL;
}

void *allocateFlushableMemory(FlushableMemory *memory, size_t size) {
if (memory->blocks == NULL) {
memory->blocks = malloc(100*sizeof(void *));
}
memory->blocks[memory->top] = malloc(size);
memory->top++;
return memory->blocks[memory->top-1];
}
13 changes: 13 additions & 0 deletions src/memory.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ extern bool memoryIsBetween(Memory *memory, void *pointer, int low, int high);
extern void memoryFreeUntil(Memory *memory, void *pointer);


/***********************************************************************/
/* New, so far, unused new Memory handling */

typedef struct {
int size;
int top;
void **blocks;
} FlushableMemory;

extern void initFlushableMemory(FlushableMemory *memory);
extern void *allocateFlushableMemory(FlushableMemory *memory, size_t size);


/***********************************************************************/

extern jmp_buf memoryResizeJumpTarget;
Expand Down
21 changes: 21 additions & 0 deletions src/memory_tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,24 @@ Ensure(Memory, will_fatal_if_reallocing_not_last_allocated) {

assert_that(internalCheckFailCalled);
}

Ensure(Memory, can_allocate_single_block_in_flushable_memory) {
FlushableMemory memory;

initFlushableMemory(&memory);

void *block = allocateFlushableMemory(&memory, 4);
assert_that(block, is_not_null);
}

Ensure(Memory, can_reallocate_block_array_for_overflow) {
FlushableMemory memory;

initFlushableMemory(&memory);

for (int i=0; i < 10000; i++) {
allocateFlushableMemory(&memory, 4);
}
void *block = allocateFlushableMemory(&memory, 4);
assert_that(block, is_not_null);
}

0 comments on commit 18b05aa

Please sign in to comment.