Memory management in C is essential for efficient and effective use of memory during program execution. C provides both static and dynamic memory allocation, and you must manage memory manually, especially for dynamic allocation.
Memory is divided into several regions:
malloc
, calloc
, realloc
, free
).malloc()
: Allocates a specified number of bytes and returns a pointer to the first byte.
void *malloc(size_t size);
Example:
int *arr = (int *) malloc(5 * sizeof(int));
calloc()
: Allocates memory for an array and initializes all bytes to zero.
void *calloc(size_t nitems, size_t size);
Example:
int *arr = (int *) calloc(5, sizeof(int));
realloc()
: Resizes an existing block of memory.
void *realloc(void *ptr, size_t size);
Example:
arr = (int *) realloc(arr, 10 * sizeof(int));
free()
: Frees dynamically allocated memory to avoid memory leaks.
void free(void *ptr);
Example:
free(arr);