Skip to content

Instantly share code, notes, and snippets.

@ammarfaizi2
Created March 20, 2022 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ammarfaizi2/db0af6aa0b95a0c7478bce64e349f021 to your computer and use it in GitHub Desktop.
Save ammarfaizi2/db0af6aa0b95a0c7478bce64e349f021 to your computer and use it in GitHub Desktop.
#include "nolibc.h"
// // Use these to test the real libc.
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include <sys/mman.h>
static void test_mmap(void)
{
const size_t len = 1024;
void *p;
p = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE,
-1, 0);
if (!p) {
puts("mmap() error");
return;
}
munmap(p, len);
}
static void test_malloc(void)
{
void *ptr, *tmp;
const size_t len1 = 4096;
const size_t len2 = 8192;
ptr = malloc(len1);
if (!ptr) {
puts("malloc() error");
return;
}
memset(ptr, 'a', len1);
tmp = realloc(ptr, len2);
if (!tmp) {
free(ptr);
puts("realloc() error");
return;
}
ptr = tmp;
memset(ptr, 'b', len2);
free(ptr);
}
static void test_calloc(void)
{
void *ptr, *tmp;
const size_t len1 = 4096;
const size_t len2 = 8192;
ptr = calloc(sizeof(char), len1);
if (!ptr) {
puts("malloc() error");
return;
}
memset(ptr, 'a', len1);
tmp = realloc(ptr, len2);
if (!tmp) {
free(ptr);
puts("realloc() error");
return;
}
ptr = tmp;
memset(ptr, 'b', len2);
free(ptr);
}
static void test_string_heap(void)
{
static const char str[] = "Hello World!";
char *x;
x = strdup(str);
if (memcmp(x, str, sizeof(str))) {
printf("Wrong strdup()!\n");
return;
}
free(x);
x = strndup(str, 5);
if (memcmp(x, str, 4) || x[5] != '\0') {
printf("Wrong strndup()!\n");
return;
}
free(x);
}
int main(void)
{
test_mmap();
test_malloc();
test_calloc();
test_string_heap();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment