Search⌘ K

The malloc() Call

Explore how to use the malloc() call in C to allocate memory dynamically on the heap. Understand the importance of specifying sizes with sizeof, casting pointers correctly, and handling strings with strlen. This lesson helps you write efficient memory allocation code and avoid common pitfalls when managing heap memory.

We'll cover the following...

The malloc() call is quite simple: you pass it a size asking for some room on the heap, and it either succeeds and gives you back a pointer to the newly-allocated space, or fails and returns NULL​.

man malloc

The manual page shows what you need to do to use malloc; type man malloc at the command line in the terminal provided below and you will see:

#include <stdlib.h>
  ...
  void *malloc(size_t size);

Terminal 1
Terminal
Loading...

From this information, you can see that all you need to do is include the header file stdlib.h to use malloc. In fact, you don’t really need to even do this, as the C library, which all C programs link with by default, has the code for malloc() inside of it; adding the header just lets the compiler check whether you are calling malloc() correctly (e.g., ...