checking that `malloc` succeeded in C

malloc returns a null pointer on failure. So, if what you received isn’t null, then it points to a valid block of memory. Since NULL evaluates to false in an if statement, you can check it in a very straightforward manner: value = malloc(…); if(value) { // value isn’t null } else { // value … Read more

Code for malloc and free

The POSIX interface of malloc is defined here. If you want to find out how the C library in GNU/Linux (glibc) implements malloc, go and get the source code from http://ftp.gnu.org/gnu/glibc/ or browse the git repository and look at the malloc/malloc.c file. There is also the base documentation of the Memory Allocator by Doug Lea … Read more

Malloc function (dynamic memory allocation) resulting in an error when it is used globally

You can’t execute code outside of functions. The only thing you can do at global scope is declaring variables (and initialize them with compile-time constants). malloc is a function call, so that’s invalid outside a function. If you initialize a global pointer variable with malloc from your main (or any other function really), it will … Read more