Search⌘ K
AI Features

Dynamic Memory Allocation Functions

Explore dynamic memory allocation in C by understanding malloc, calloc, and free functions. Learn how to allocate, initialize, and deallocate memory on the heap safely to prevent leaks and errors.

Introduction

We want to figure out how to allocate memory on the heap. Unlike stack allocations, we have to use specialized functions to allocate memory on the stack.

These functions are as follows:

  • malloc
  • calloc
  • free

We must include the stdlib.h header file to use dynamic allocation functions.

The malloc function

The malloc function is the most common memory allocation function.

Prototype:

void *malloc(size_t size);
  • It allocates a block of size bytes.
  • It returns a pointer to the beginning of the allocated memory block or NULL if the allocation fails (not enough space, for example).
  • In the prototype, the return type is a void pointer. Let’s ignore this aspect for now. Just assume that it returns the data type that we need. We’ll explore genericity using void pointers in the upcoming lessons

The malloc function doesn’t care about data types. It allocates some bytes, and that’s it. The memory is just a sequence of bytes and knows nothing of data types. The difference comes from how we interpret the memory ...