Last active
February 23, 2022 16:43
-
-
Save opsJson/93586addea5c678bad0fbd8bf363b8de to your computer and use it in GitHub Desktop.
Stores the size of allocated memory before the void * given by memory allocation functions. You can get it easily with msize();
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> | |
| void *__malloc__(size_t size) { | |
| size_t *memory; | |
| memory = (size_t*)malloc(sizeof(size_t) + size); | |
| if (memory == NULL) return NULL; | |
| *memory = size; | |
| memory += 1; | |
| return (void*)memory; | |
| } | |
| void *__calloc__(size_t num, size_t size) { | |
| size_t *memory; | |
| memory = (size_t*)calloc(num, size + sizeof(size_t)); | |
| if (memory == NULL) return NULL; | |
| *memory = num * size; | |
| memory += 1; | |
| return (void*)memory; | |
| } | |
| void __free__(void *memory) { | |
| size_t *ptr; | |
| ptr = (size_t*)memory; | |
| ptr -= 1; | |
| free(ptr); | |
| } | |
| void *__realloc__(void *memory, size_t newSize) { | |
| size_t *ptr; | |
| ptr = (size_t*)memory; | |
| ptr -= 1; | |
| ptr = (size_t*)realloc(ptr, newSize + sizeof(size_t)); | |
| if (ptr == NULL) return NULL; | |
| *ptr = newSize; | |
| ptr += 1; | |
| return (void*)ptr; | |
| } | |
| size_t msize(void *memory) { | |
| size_t *ptr; | |
| ptr = (size_t*)memory; | |
| ptr -= 1; | |
| return *ptr; | |
| } | |
| #define malloc(size) __malloc__(size) | |
| #define calloc(num, size) __calloc__(num, size) | |
| #define free(memory) __free__(memory) | |
| #define realloc(memory, newSize) __realloc__(memory, newSize) | |
| /*/////////////////////////////////// | |
| Testing: | |
| ///////////////////////////////////*/ | |
| #include <string.h> | |
| int main(void) { | |
| char *str = malloc(1024); | |
| strcpy(str, "Hello, world!"); | |
| printf("%s\n", str); | |
| printf("%i\n", msize(str)); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment