Initial commit

This commit is contained in:
2026-03-06 08:51:02 -06:00
commit 0c69151528
10 changed files with 502 additions and 0 deletions

31
tests/01_malloc.c Normal file
View File

@@ -0,0 +1,31 @@
#define DEBUG
#include <stdlib.h>
#include <string.h>
#include "../include/mem.h"
int mem_is_zero(const void *ptr, size_t nbytes) {
assert(ptr);
assert(nbytes > 0);
static const unsigned char zero_block[1024] = {0};
while (nbytes >= sizeof(zero_block)) {
if (memcmp(ptr, zero_block, sizeof(zero_block)) != 0)
return 0;
ptr = (const unsigned char *)ptr + sizeof(zero_block);
nbytes -= sizeof(zero_block);
}
if (nbytes > 0 && memcmp(ptr, zero_block, nbytes) != 0)
return 0;
return 1;
}
int main(void){
size_t nbytes = 4096;
void *tmp = malloc(nbytes);
memset(tmp, 0xAB, nbytes);
free(tmp);
void *ptr = ALLOC(nbytes); // likely gets the same region back
assert(!mem_is_zero(ptr, nbytes)); // FAILS — 0xAB still there
assert(ptr != NULL);
return EXIT_SUCCESS;
}

27
tests/02_calloc.c Normal file
View File

@@ -0,0 +1,27 @@
#define DEBUG
#include <stdlib.h>
#include <string.h>
#include "../include/mem.h"
int mem_is_zero(const void *ptr, size_t nbytes) {
assert(ptr);
assert(nbytes > 0);
static const unsigned char zero_block[1024] = {0};
while (nbytes >= sizeof(zero_block)) {
if (memcmp(ptr, zero_block, sizeof(zero_block)) != 0)
return 0;
ptr = (const unsigned char *)ptr + sizeof(zero_block);
nbytes -= sizeof(zero_block);
}
if (nbytes > 0 && memcmp(ptr, zero_block, nbytes) != 0)
return 0;
return 1;
}
int main(void){
size_t nbytes = 4096;
void *ptr = CALLOC(1,nbytes);
assert(ptr != NULL);
assert( mem_is_zero(ptr, nbytes));
return EXIT_SUCCESS;
}

28
tests/03_exception.c Normal file
View File

@@ -0,0 +1,28 @@
#define DEBUG
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include "../include/mem.h"
int main(void){
size_t nbytes = MEM_GB(1024);
void *buf;
TRY {
buf = ALLOC(nbytes); /* try 1GB */
if (!buf)
RAISE(oom);
free(buf);
}
EXCEPT(oom) {
/* handle memory failure gracefully */
fprintf(stderr, "Caught: %s\n", oom.reason);
return EXIT_SUCCESS; /* requested behavior */
}
FINALLY {
/* cleanup if needed, runs always */
if (buf) free(buf);
}
END_TRY;
return EXIT_FAILURE; /* shouldn't reach here for this example */
}