The <stdlib.h> (Standard Library) header file defines several general-purpose functions, including dynamic memory management, random number generation, communication with the environment, integer arithmetic, and searching/sorting utilities.
Unlike standard arrays where the size is fixed at compile time, <stdlib.h> allows you to allocate memory dynamically during program execution (at runtime) on the Heap.
malloc(size): Allocates a block of memory of the specified size (in bytes). Does not initialize the memory.calloc(n, size): Allocates memory for an array of n elements, initializing all bytes to zero.realloc(ptr, new_size): Resizes a previously allocated memory block.free(ptr): Deallocates previously allocated memory to prevent memory leaks.#include <stdio.h> #include <stdlib.h>int main() { // Allocate memory for an array of 5 integers int *arr = (int *) malloc(5 * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; } arr[0] = 10; printf("First element: %d\n", arr[0]); // Always free dynamically allocated memory! free(arr); return 0; }
Sometimes you need to terminate a program immediately, especially if a critical error occurs.
exit(status): Terminates the program. exit(0) generally signifies successful termination, while non-zero values (like exit(1)) indicate an error.<stdlib.h> provides useful functions for converting numeric strings into actual numbers:
atoi(): Converts a string to an int.atof(): Converts a string to a double.atol(): Converts a string to a long int.#include <stdio.h> #include <stdlib.h>int main() { char str[] = "2024"; int year = atoi(str); printf("Next year is: %d\n", year + 1); return 0; }
Which function from <stdlib.h> is used to deallocate memory to prevent memory leaks?