C stdlib.h Library

C Tutorial

C stdlib.h Library

In C stdlib.h Library stands for Standard Library. It provides general-purpose functions for:

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

  1. Always check the return of malloc/calloc/realloc for NULL.

  2. Use free() to avoid memory leaks.

  3. rand() generates pseudo-random numbers, use srand() to seed.

  4. qsort() and bsearch() are powerful for arrays of structs or complex data.

You may also like...