diff --git a/examples/malloc_example.corth b/examples/malloc_example.corth index 6206647..f473784 100644 --- a/examples/malloc_example.corth +++ b/examples/malloc_example.corth @@ -3,17 +3,20 @@ include "core/stack.corth" macro malloc:ARRAY-SIZE 0x4000 endmacro macro malloc:AVAIL-STACK-SIZE 0x100 endmacro -include "dynamic/malloc.corth" include "dynamic/debug_malloc.corth" +memory index sizeof(int) end + proc allocate-space int -> ptr in let size in - size malloc let object in + size index @64 malloc let object in object mlength size != if "[INFO] Size does not match.\n" puts + 1 exit drop else - "[INFO] Successfully allocated object.\n" puts + "[INFO] Successfully allocated object with index " puts index @64 puti ".\n" puts + index @inc64 end STDOUT debug-dynamic-memory @@ -24,10 +27,13 @@ end end proc deallocate-space ptr -> in let container in - container mfree if - "[INFO] Successfully deallocated object.\n" puts - else - "[INFO] Could not deallocate object.\n" puts + container debug-malloc:get-tag let tag in + container mfree if + "[INFO] Successfully deallocated object with index " puts tag puti ".\n" puts + else + "[INFO] Could not deallocate object.\n" puts + 1 exit drop + end end STDOUT debug-dynamic-memory @@ -37,6 +43,7 @@ proc main int int -> int in let argc argv in malloc:init + 0 index !64 STDOUT debug-dynamic-memory diff --git a/std/dynamic/debug_malloc.corth b/std/dynamic/debug_malloc.corth index d35f8ef..0f43b3d 100644 --- a/std/dynamic/debug_malloc.corth +++ b/std/dynamic/debug_malloc.corth @@ -1,6 +1,6 @@ include "linux_x86/sys.corth" include "linux_x86/io/output.corth" -include "dynamic/malloc.corth" +include "dynamic/_malloc.corth" // Can be used to debug malloc segments. @@ -54,7 +54,7 @@ in true end -// Can bu used to see how much space is available and to check memory leaks. +// Can be used to check the space available and to check memory leaks. proc get-available-dynamic-memory -> int in @@ -68,3 +68,19 @@ in sum @64 end end + +macro malloc:init malloc:_init endmacro + +// This returns a shifted pointer. +// The created dynamicly-placed object contains debug tag information which is hidden from the user. +macro malloc let _size_ _debug_ in + size 8 + _malloc peek _obj_ in _obj_ isn-null if + _debug_ _obj_ !64 + end end 8 + +end endmacro +macro mfree 8 - _mfree endmacro +macro mfree-deep _mfree-deep endmacro +macro mlength 8 - _mlength 8 - endmacro + +macro debug-malloc:get-tag 8 - @64 endmacro +macro debug-malloc:set-tag 8 - !64 endmacro