Created
February 24, 2013 15:07
-
-
Save homelinen/5024153 to your computer and use it in GitHub Desktop.
Very Simple Malloc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include "malloc.h" | |
#include "chunk.h" | |
/* Globals */ | |
Chunk* chunks; | |
void* mem_start; | |
void new_chunk(Chunk*, size_t); | |
Chunk* find_last_chunk() { | |
Chunk* temp_chunk = chunks; | |
while (temp_chunk->next) { | |
temp_chunk = temp_chunk->next; | |
} | |
return temp_chunk; | |
} | |
void* xmalloc(size_t size) { | |
Chunk* new_address = 0; | |
Chunk* temp_chunk; | |
// Get next free address (end of LList) | |
temp_chunk = find_last_chunk(); | |
new_address = temp_chunk + temp_chunk->size + 1; | |
Chunk* n_chunk = (Chunk*) new_address; | |
new_chunk(n_chunk, size); | |
temp_chunk->next = n_chunk; | |
// Return this address | |
return(new_address + sizeof(Chunk)); | |
} | |
void new_chunk(Chunk* chunk, size_t sz) { | |
chunk->size = sz; | |
chunk->on = 1; | |
chunk->next = 0; | |
} | |
int main(int argc, char** args) { | |
int memsize = 1024*1024*1024; | |
// Assign memory | |
mem_start = sbrk(memsize); | |
printf("Memstart: %p\n", mem_start); | |
chunks = 0; | |
chunks = mem_start; | |
new_chunk(chunks, 0); | |
printf("Made it this far\n"); | |
int* tests[200]; | |
int i; | |
for (i = 0; i < 200; i++) { | |
tests[i] = xmalloc(sizeof(int)); | |
*tests[i] = i; | |
} | |
for (i; i >= 0; i--) { | |
printf("%d ", *tests[i]); | |
} | |
printf("\n"); | |
// Free all the memory | |
sbrk(-memsize); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment