From 5dfa2823a0ee23303c9e1dd7e38833e3e6e01396 Mon Sep 17 00:00:00 2001 From: Manuel Traut Date: Wed, 9 Jan 2019 17:18:55 +0100 Subject: add a malloc example it demonstrates that memory is only allocated if used. Signed-off-by: Manuel Traut --- schulung_tools/malloc/malloc.c | 57 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 schulung_tools/malloc/malloc.c (limited to 'schulung_tools/malloc/malloc.c') diff --git a/schulung_tools/malloc/malloc.c b/schulung_tools/malloc/malloc.c new file mode 100644 index 0000000..a636426 --- /dev/null +++ b/schulung_tools/malloc/malloc.c @@ -0,0 +1,57 @@ +#include +#include +#include +#include + +#define NUM_OF_GBYTES 8 + +/* if verbose is enabled forks are done for printing additional informations */ +#define VERBOSE 0 + +#if VERBOSE +/* forking is not always possible if memory is low */ +#define sys(cmd) if(system(cmd) == -1) printf("%s failed\n", cmd); +#else +#define sys(cmd) ; +#endif + +#define MEMFREE "free -h" + +int main(void) +{ + char *p[NUM_OF_GBYTES]; + int i; + + printf("memory usage:\n"); + sys(MEMFREE); + printf("\n\n"); + + for (i = 0; i < NUM_OF_GBYTES; i++) { + p[i] = malloc(1024 * 1024 * 1024); + printf("allocated 1GB: %p\n", p[i]); + sys(MEMFREE); + } + + printf("\n\n"); + + for (i = 0; i < NUM_OF_GBYTES; i++) { + if (p[i]) { + printf("memsetting 1GB: %p\n", p[i]); + sys("date +%s.%N"); + memset(p[i], 1, 1024 * 1024 * 1024); + sys("date +%s.%N"); + sys(MEMFREE); + } + } + + printf("\n\n"); + + for (i = 0; i < NUM_OF_GBYTES; i++) { + if (p[i]) { + printf("free 1GB: %p\n", p[i]); + free(p[i]); + sys(MEMFREE); + } + } + return 0; +} -- cgit v1.2.3