Memory management
suggest changeIntroduction
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
name | description |
|———|––––––––| | 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 | | nelements | number of elements | | ptr | pointer to allocated memory previously returned by malloc, calloc, realloc or aligned_alloc | | alignment | alignment of allocated memory
Remarks
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()).