aboutsummaryrefslogtreecommitdiff
path: root/lib/malloc
diff options
context:
space:
mode:
Diffstat (limited to 'lib/malloc')
-rw-r--r--lib/malloc/malloc.c45
-rw-r--r--lib/malloc/malloc.h5
2 files changed, 46 insertions, 4 deletions
diff --git a/lib/malloc/malloc.c b/lib/malloc/malloc.c
index a0e9ebf..e941c31 100644
--- a/lib/malloc/malloc.c
+++ b/lib/malloc/malloc.c
@@ -113,6 +113,47 @@ void free(void *ptr)
/** DOC
* @type function
+ * @name realloc
+ *
+ * @param void *ptr
+ * @param u64 size
+ * @return void*
+ *
+ * @description
+ * Copies content of *ptr to a new location and returns new adress.
+ */
+void *realloc(void *ptr, u64 size)
+{
+ segment_t *seg = mbrk.first;
+ void *mem;
+ char *d;
+
+ for (; seg; seg = seg->next) {
+ if (ptr == seg->ptr)
+ break;
+ }
+
+ if (!seg)
+ return 0;
+
+ if (seg->size == size)
+ return seg->ptr;
+
+ mem = malloc(size);
+ d = mem;
+
+ for (const char *p = (const char*)ptr; p < (const char*)ptr + seg->size; ++p) {
+ *(d++) = *p;
+ }
+
+ free(ptr);
+
+ return mem;
+}
+
+
+/** DOC
+ * @type function
* @name __initialize_memory
*
* @description
@@ -143,7 +184,7 @@ segment_t *__find_free_segment(u64 size)
segment_t * seg = mbrk.first;
for (; seg; seg = seg->next) {
- if (seg->free && size == seg->size)
+ if (seg->free && seg->size == size)
return seg;
}
@@ -171,7 +212,7 @@ segment_t *__allocate_new(u64 size)
brk((void*)mbrk.current);
segment_t *seg = (segment_t*)last;
- seg->ptr = (void*)(mbrk.current - size);
+ seg->ptr = (void*)(last + sizeof(segment_t));
seg->size = size;
seg->free = 0;
seg->next = 0;
diff --git a/lib/malloc/malloc.h b/lib/malloc/malloc.h
index d4896bf..f05a6b2 100644
--- a/lib/malloc/malloc.h
+++ b/lib/malloc/malloc.h
@@ -3,7 +3,8 @@
#include "../sys/sizes.h"
-void * malloc(u64 size);
-void free(void * ptr);
+void *malloc(u64 size);
+void *realloc(void *ptr, u64 size);
+void free(void *ptr);
#endif