C <stdlib.h>

C <stdlib.h>: Standard Library Functions

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.


1. Dynamic Memory Allocation

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.

Memory Allocation Example:

#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; }


2. Process Control (Exit)

Sometimes you need to terminate a program immediately, especially if a critical error occurs.


3. String Conversion Functions

<stdlib.h> provides useful functions for converting numeric strings into actual numbers:

String to Integer Example:

#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; }


Exercise

?

Which function from <stdlib.h> is used to deallocate memory to prevent memory leaks?