From fffc8d92da45187fac1860b283cd7356bb0a033c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciro=20Santilli=20=E5=85=AD=E5=9B=9B=E4=BA=8B=E4=BB=B6=20?= =?UTF-8?q?=E6=B3=95=E8=BD=AE=E5=8A=9F?= Date: Wed, 18 Sep 2019 00:00:02 +0000 Subject: [PATCH] memory leak example --- README.adoc | 14 ++++++++++++-- userland/c/memory_leak.c | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 userland/c/memory_leak.c diff --git a/README.adoc b/README.adoc index 37f25dd..be3138d 100644 --- a/README.adoc +++ b/README.adoc @@ -12857,7 +12857,9 @@ Allocate memory! Vs using the stack: https://stackoverflow.com/questions/4584089 link:userland/c/malloc.c[]: `malloc` hello world: allocate two ints and use them. -LInux 5.1 / glibc 2.29 implements it with the <>. +Linux 5.1 / glibc 2.29 implements it with the <>. + +`malloc` leads to the infinite joys of <>. ===== malloc implementation @@ -13125,7 +13127,15 @@ Let's group the hard-to-debug undefined-behaviour-like stuff found in C / C+ her https://stackoverflow.com/questions/1345670/stack-smashing-detected/51897264#51897264 -link:userland/c/smash_stack.c[] +Example:: link:userland/c/smash_stack.c[] + +Leads to the dreadful "Stack smashing detected" message. Which is infinitely better than a silent break in any case. + +==== Memory leaks + +How to debug: https://stackoverflow.com/questions/6261201/how-to-find-memory-leak-in-a-c-code-project/57877190#57877190 + +Example: link:userland/c/memory_leak.c[] === Userland content bibliography diff --git a/userland/c/memory_leak.c b/userland/c/memory_leak.c new file mode 100644 index 0000000..155ff0b --- /dev/null +++ b/userland/c/memory_leak.c @@ -0,0 +1,23 @@ +/* https://cirosantilli.com/linux-kernel-module-cheat#memory-leaks */ + +#include + +void * my_malloc(size_t n) { + return malloc(n); +} + +void leaky(size_t n, int do_leak) { + void *p = my_malloc(n); + if (!do_leak) { + free(p); + } +} + +int main(void) { + leaky(0x10, 0); + leaky(0x10, 1); + leaky(0x100, 0); + leaky(0x100, 1); + leaky(0x1000, 0); + leaky(0x1000, 1); +}