memory leak example

This commit is contained in:
Ciro Santilli 六四事件 法轮功
2019-09-18 00:00:02 +00:00
parent 5378cb295b
commit fffc8d92da
2 changed files with 35 additions and 2 deletions

View File

@@ -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 <<mmap,`mmap` system call>>.
Linux 5.1 / glibc 2.29 implements it with the <<mmap,`mmap` system call>>.
`malloc` leads to the infinite joys of <<memory-leaks>>.
===== 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

23
userland/c/memory_leak.c Normal file
View File

@@ -0,0 +1,23 @@
/* https://cirosantilli.com/linux-kernel-module-cheat#memory-leaks */
#include <stdlib.h>
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);
}