summaryrefslogtreecommitdiff
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
parent16c579d5fbb7ac62bf2f6f105d56d46e7409f74e (diff)
add a malloc example
it demonstrates that memory is only allocated if used. Signed-off-by: Manuel Traut <manut@linutronix.de>
-rw-r--r--schulung_tools/malloc/Makefile7
-rw-r--r--schulung_tools/malloc/README5
-rw-r--r--schulung_tools/malloc/malloc.c57
3 files changed, 69 insertions, 0 deletions
diff --git a/schulung_tools/malloc/Makefile b/schulung_tools/malloc/Makefile
new file mode 100644
index 0000000..b6160a8
--- /dev/null
+++ b/schulung_tools/malloc/Makefile
@@ -0,0 +1,7 @@
+malloc: malloc.c
+ $(CROSS_COMPILE)gcc -g -omalloc malloc.c
+
+clean:
+ rm -f malloc core
+
+.PHONY: clean
diff --git a/schulung_tools/malloc/README b/schulung_tools/malloc/README
new file mode 100644
index 0000000..77b18cd
--- /dev/null
+++ b/schulung_tools/malloc/README
@@ -0,0 +1,5 @@
+This program demonstrates that a processes is not actually assigned memory
+until it page-faults on the pages.
+
+WARNING: This program might fill your RAM and cause the Linux OOM Killer to
+ be invoked.
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;
+}