C Language Memory management

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

For managing dynamically allocated memory, the standard C library provides the functions malloc(), calloc(), realloc() and free(). In C99 and later, there is also aligned_alloc(). Some systems also provide alloca().

Syntax

  • void *aligned_alloc(size_t alignment, size_t size); /* Only since C11 */
  • void *calloc(size_t nelements, size_t size);
  • void free(void *ptr);
  • void *malloc(size_t size);
  • void *realloc(void *ptr, size_t size);
  • void *alloca(size_t size); /* from alloca.h, not standard, not portable, dangerous. */

Parameters

namedescription
size (malloc, realloc and aligned_alloc)total size of the memory in bytes. For aligned_alloc the size must be a integral multiple of alignment.
size (calloc)size of each element
nelementsnumber of elements
ptrpointer to allocated memory previously returned by malloc, calloc, realloc or aligned_alloc
alignmentalignment of allocated memory

Remarks

C11

Note that aligned_alloc() is only defined for C11 or later.

Systems such as those based on POSIX provide other ways of allocating aligned memory (e.g. posix_memalign()), and also have other memory management options (e.g. mmap()).



Got any C Language Question?