The stdlib.h
header is a crucial component of the C standard library. It provides a wide array of general-purpose functions, including dynamic memory management, random number generation, and string conversion utilities.
The stdlib.h
header offers essential functions for dynamic memory allocation:
malloc()
: Allocates memorycalloc()
: Allocates and initializes memoryrealloc()
: Resizes allocated memoryfree()
: Deallocates memory
#include <stdlib.h>
#include <stdio.h>
int main() {
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}
The stdlib.h
header provides functions for generating random numbers:
rand()
: Generates a pseudo-random integersrand()
: Seeds the random number generator
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 5; i++) {
printf("%d ", rand() % 100);
}
return 0;
}
atoi()
, atof()
, atol()
: Convert strings to numeric typesabs()
, labs()
: Compute absolute valuesqsort()
: Implements the quicksort algorithmbsearch()
: Performs a binary search on a sorted arrayexit()
: Terminates the programfree()
to deallocate memory allocated with malloc()
, calloc()
, or realloc()
to prevent memory leaks.srand()
only once, typically at the start of your program.atoi()
as they don't provide error checking for invalid input.The stdlib.h
header is an indispensable part of C programming. It provides a rich set of functions for common tasks, enhancing the capabilities of C programs. By mastering these functions, developers can write more efficient and robust C code.
For more information on C programming fundamentals, explore our guides on C data types and C function declarations.