C - Purpose of stdlib.h
In C, stdlib.h
stands for Standard Library Header.
It provides functions for general-purpose utilities — such as memory allocation, process control, conversions, random numbers, and searching/sorting.
1. Purpose of stdlib.h
When you include:
#include <stdlib.h>
you get:
-
Function prototypes for commonly used utility functions.
-
Macros for constants like
EXIT_SUCCESS
andEXIT_FAILURE
. -
Type definitions like
size_t
,div_t
,ldiv_t
.
Without including it, you may get compiler warnings or errors when calling these functions.
2. Major Features Provided by stdlib.h
a) Memory Management
-
malloc(size_t size)
– Allocates memory -
calloc(size_t n, size_t size)
– Allocates and initializes memory to zero -
realloc(void *ptr, size_t size)
– Changes size of previously allocated memory -
free(void *ptr)
– Frees allocated memory
b) Process Control
-
exit(int status)
– Ends the program with a status code -
abort()
– Immediately terminates the program abnormally -
system(const char *command)
– Runs a system command
c) Conversions
-
String to numbers
-
atoi(const char *str)
– String toint
-
atof(const char *str)
– String todouble
-
atol(const char *str)
– String tolong
-
strtol()
,strtoul()
,strtod()
– Safer, more flexible conversions
-
-
Number to string
-
Usually handled via
sprintf()
fromstdio.h
, but combined withstdlib.h
conversions for data processing.
-
d) Random Numbers
-
rand()
– Generates pseudo-random numbers (0 toRAND_MAX
) -
srand(unsigned int seed)
– Seeds the random number generator
e) Searching and Sorting
-
qsort()
– General-purpose quicksort function -
bsearch()
– Binary search function for sorted arrays
f) Arithmetic Functions
-
abs(int n)
– Absolute value of integer -
labs(long n)
– Absolute value of long integer -
div()
,ldiv()
– Integer division returning quotient and remainder in a struct
g) Important Macros
-
EXIT_SUCCESS
– Successful program termination (usually0
) -
EXIT_FAILURE
– Unsuccessful program termination (non-zero) -
RAND_MAX
– Maximum value returned byrand()
3. Example
#include <stdio.h>
#include <stdlib.h>
int main() {
// Random number example
srand(42);
printf("Random: %d\n", rand());
// Memory allocation example
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < 5; i++) arr[i] = i + 1;
for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return EXIT_SUCCESS;
}