C stdlib.h Library
C stdlib.h Library
The stdlib.h library in C stands for Standard Library. It provides general-purpose functions for:
-
Memory management
-
Program control
-
Conversions
-
Random numbers
-
Searching and sorting
It is one of the most commonly used standard libraries in C.
📌 Common Categories & Functions
1️⃣ Memory Management
| Function | Description |
|---|---|
malloc(size_t size) |
Allocates memory dynamically, returns pointer |
calloc(size_t n, size_t size) |
Allocates zero-initialized memory |
realloc(void *ptr, size_t size) |
Resizes previously allocated memory |
free(void *ptr) |
Frees allocated memory |
Example:
2️⃣ Program Control
| Function | Description |
|---|---|
exit(int status) |
Terminates program immediately |
abort() |
Aborts program |
atexit(void (*func)(void)) |
Registers a function to run at program exit |
Example:
3️⃣ Random Numbers
| Function | Description |
|---|---|
rand() |
Returns pseudo-random number |
srand(unsigned int seed) |
Sets seed for rand() |
Example:
4️⃣ String Conversion
| Function | Description |
|---|---|
atoi(const char *str) |
Convert string to integer |
atof(const char *str) |
Convert string to float |
atol(const char *str) |
Convert string to long |
strtol, strtod |
Advanced conversion with error checking |
Example:
5️⃣ Searching and Sorting
| Function | Description |
|---|---|
qsort(void *base, size_t nitems, size_t size, int (*compar)(const void*,const void*)) |
Sorts an array |
bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void*,const void*)) |
Binary search in sorted array |
Example: Sorting integers
6️⃣ Dynamic Memory + Struct Example
📌 Summary Table
| Category | Functions |
|---|---|
| Memory Management | malloc, calloc, realloc, free |
| Program Control | exit, abort, atexit |
| Random Numbers | rand, srand |
| String Conversion | atoi, atof, atol, strtol, strtod |
| Searching & Sorting | qsort, bsearch |
✅ Notes
-
Always check the return of
malloc/calloc/reallocfor NULL. -
Use
free()to avoid memory leaks. -
rand()generates pseudo-random numbers, usesrand()to seed. -
qsort()andbsearch()are powerful for arrays of structs or complex data.
