Professional Documents
Culture Documents
This program is creating binary trees and showing the use of memory
allocation and deallocation.
#include <stddef.h>
#include <unistd.h>
#include <string.h>
/**
* As suggested, two binary search trees are used to organize the free
blocks.
*/
struct tnode { /* a tree node */
struct tnode *left, *right;
/* every allocated data block has a header before the returned address
* to store the meta data of this block,
* which includes the binary seach tree nodes */
struct header {
struct tnode nodes[2];
};
/* try to merge free blocks with continous space using the space
binary tree */
static struct tnode *merge(struct tnode *node);
/*
* free the allocated the memory space.
* Assume the ptr is a valid space allocated before using the malloc()
function.
* */
void free(void *ptr)
{
if (ptr != NULL) {
/* calculate the address of the header */
release_block(HEADER(ptr));
}
}
if (ptr == NULL) {
return malloc(size);
}
return nptr;
}
if (curr == NULL) {
/* no allocated space for the requested size, use sbrk() to
allocate one */
h = sbrk(size + sizeof(struct header));
/* initialize the header */
h->nodes[0].value = size;
h->nodes[1].value = (size_t)h;
return h;
}
h->nodes[0].value = size;
return h;
}
if (node == NULL) {
return node;
}
node->left = merge(node->left);
node->right = merge(node->right);
if (node == NULL) {
/* reach a null branch, simply return the node of the block */
h->left = NULL;
h->right = NULL;
return h;
}
return node;
}