4 ms·
teaching C and not checking malloc, bad idea. using realloc in the way its used in this "tutorial" can cause memory leaks. realloc should be checked before rea
by halayli 11y ago
teaching C and not checking malloc, bad idea. using realloc in the way its used in this "tutorial" can cause memory leaks. realloc should be checked before reassigned because it can return NULL and that will overwrite the previous valid memory address.
- mappu 11y ago>teaching C and not checking malloc, bad idea On Linux, malloc will appear to give you memory even if there is none left to give, so checking the error is not important.
- halayli 11y agoIf you take such assumptions when writing production software, good luck. You need to program based on what the man page says and it's clear even in linux that it can still return a NULL when overcommit is turned off.
- masklinn 11y agoAn issue which is not linux specific is when calculating the size of an array allocation you can overflow size_t. So when mallocing arrays, you're supposed to check the computed size for overflow (or use calloc(3) or OpenBSD/libbsd's reallocarray(3) instead).
- pdw 11y agoNot checking malloc's return value can easily lead to security vulnerabilities, particularly in bytecode interpreters and things like that. The basic plan is simple: Trick the target program into allocating an impossible huge block of memory (e.g. 3 gigabyte on a 32 bit system). Malloc will return NULL but the program blindly assumes the allocation has succeeded. Now use carefully chosen indices to read and write whatever memory you want. As an example, here's a classic Flash exploit that used this technique: http://chargen.matasano.com/chargen/2007/7/27/this-new-vulnerability-dowds-inhuman-flash-exploit.html http://chargen.matasano.com/chargen/2007/7/27/this-new-vulne... Really, xmalloc is five lines of code. Just use it. void *xmalloc(size_t size) { void *ptr = malloc(size); if (!ptr) abort(); return ptr; }