Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

malloc free sizeof

Name: Anonymous 2012-01-13 9:51

How do I implement a simple mallow, free, and widely in ask x86?
How does free know how much to actually free?

Name: Anonymous 2012-01-13 11:01

This is the simplest conforming malloc implementation that doesn't just return NULL.
#include <string.h>
#ifndef NULL
#define NULL ((void *)0)
#endif
#define SOME_BIG_NUMBER (1024*1024*1024)
static char malloc_space[SOME_BIG_NUMBER];
void *malloc(size_t n) {
     static char *p = malloc_space;
     char *q = p;
     if (p+n > &malloc_space[SOME_BIG_NUMBER]) return NULL;
     p += n;
     return q;
}

void *calloc(size_t nelem, size_t elsize) {
     /* uninitialized static variables are zero */
     return malloc(nelem*elsize);
}

void *realloc(void *p, size_t n) {
     char *q = malloc(n);
     if (q) memmove(q, p, n);
     return q;
}

void free(void *p) {
     /* do nothing */
}

Newer Posts