Memory management

Download c eBook

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()).

Related Examples

Stats

1580 Contributors: 30
Wednesday, June 14, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook