Skip to content

Instantly share code, notes, and snippets.

@stefafafan
Last active December 25, 2015 01:29
Show Gist options
  • Save stefafafan/6895641 to your computer and use it in GitHub Desktop.
Save stefafafan/6895641 to your computer and use it in GitHub Desktop.
Some of my malloc implementation
#include <unistd.h> // for sbrk()
// Store free memory.
typedef struct free_list{
int size;
struct free_list *next;
struct free_list *before;
} *Free_list;
Free_list f = NULL;
void *meh_malloc1(unsigned int size)
{
char *p;
// FIrst time malloc called.
if (f == NULL)
{
// Allocate a bunch of memory with 12 bytes for header.
// If size is less than 3, 10*size is not enough so allocate 40.
if (size > 3)
{
p = sbrk(10*size);
f = (void *) p;
f -> size = 10*size - 12;
}
else
{
p = sbrk(40);
f = (void *) p;
f -> size = 40 - 12;
}
f -> next = NULL;
f -> before = NULL;
// 8 byte header after (p + 12) which has the actual size to be used and the checksum.
*(p + 12) = size; // Actual size to be returned.
*(p + 12 + 4) = 0; // Checksum.
// This chunk is not available any more.
f -> size = 0;
// Set the next attributes.
f -> next = (void *) p + 20 + size;
if (size > 3)
f -> next -> size = 10*size - (12 + 8+ size + 12);
else
f -> next -> size = 40 - (12 + 8 + size + 12);
f -> next -> next = NULL;
f -> next -> before = (void *) p;
// Return the space requested from user.
return p + 20;
}
// Not the first time malloc called.
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment