Initial commit

This commit is contained in:
2026-02-15 11:54:20 -06:00
commit 7c4f56c717
11 changed files with 478 additions and 0 deletions

28
tests/01_malloc.c Normal file
View File

@@ -0,0 +1,28 @@
#define DEBUG
#include <stdlib.h>
#include <string.h>
#include <assert.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 = 20;
void *ptr = ALLOC(0, nbytes);
assert(ptr != NULL);
assert( mem_is_zero(ptr, nbytes));
return EXIT_SUCCESS;
}

30
tests/02_calloc.c Normal file
View File

@@ -0,0 +1,30 @@
#define DEBUG
#include <stdlib.h>
#include <string.h>
#include <assert.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 = 20;
void *ptr = ALLOC(NOZERO, nbytes);
assert(ptr != NULL);
assert( !mem_is_zero(ptr, nbytes));
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,13 @@
#define DEBUG
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include "../include/mem.h"
int main(void){
size_t nbytes = MEM_GB(1024);
void *ptr = ALLOC(SOFT_FAIL, nbytes);
assert(ptr == NULL);
return EXIT_SUCCESS;
}

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(0,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 */
}