summaryrefslogtreecommitdiff
path: root/schulung_tools/malloc/malloc.c
diff options
context:
space:
mode:
authorManuel Traut <manut@linutronix.de>2019-01-09 17:18:55 +0100
committerJohn Ogness <john.ogness@linutronix.de>2019-01-28 19:47:53 +0106
commit5dfa2823a0ee23303c9e1dd7e38833e3e6e01396 (patch)
treefd37351df751aefaeb1b12f19607f6c1c5f6f7cf /schulung_tools/malloc/malloc.c
parent16c579d5fbb7ac62bf2f6f105d56d46e7409f74e (diff)
add a malloc example
it demonstrates that memory is only allocated if used. Signed-off-by: Manuel Traut <manut@linutronix.de>
Diffstat (limited to 'schulung_tools/malloc/malloc.c')
-rw-r--r--schulung_tools/malloc/malloc.c57
1 files changed, 57 insertions, 0 deletions
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 <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+
+#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;
+}