Memory allocation creates storage at runtime rather than through ordinary declarations. The allocated region initially appears as a byte array; it acquires an object type when a value is stored in it. Its lifetime and visibility therefore differ from those of declared variables. section 13.0
#include <stdlib.h> void* malloc(size_t size); void free(void* ptr); void* calloc(size_t nmemb, size_t size); void* realloc(void* ptr, size_t size); void* aligned_alloc(size_t alignment, size_t size);
The standard allocation interface includes malloc and free, plus specialized operations for zeroed storage, resizing, and alignment. section 13.1
Use allocation functions with these constraints:
- Call malloc to obtain storage and free to release it; use calloc for zeroed bits, realloc to grow or shrink storage, and aligned_alloc for nondefault alignment. section 13.1
- Pass a size strictly greater than zero to allocation functions. section 13.1
- Check the returned pointer before using the storage: a failed allocation produces a null pointer. section 13.1
- Include <stdlib.h> so the compiler sees the correct allocation interfaces; omitting it can produce an invalid assumed declaration. section 13.1
Allocate and release a vector
size_t length = livingPeople(); double *largeVec = malloc(length * sizeof *largeVec); if (largeVec) { for (size_t i = 0; i < length; ++i) largeVec[i] = 0.0; /* use largeVec */ free(largeVec); } The program computes the required runtime size, initializes each element explicitly, and releases the storage when it is no longer needed. section 13.1










