C Standard Library: , , & Deep-Dive Masterclass
Welcome to Phase 17 (Chapter 44): C Standard Library Deep-Dive โ <stdio.h>, <stdlib.h>, <math.h> & <string.h> Masterclass! The C Standard Library (libc) is the foundation of all C programs. Every function from printf() to malloc() to sin() lives here. In this guide you master the most essential headers and their production usage patterns.
| Function | Purpose |
|---|---|
printf(fmt, ...) | Formatted output to stdout. |
fprintf(fp, fmt, ...) | Formatted output to file stream. |
sprintf(buf, fmt, ...) | Formatted output to string buffer (dangerous โ no size limit). |
snprintf(buf, n, fmt, ...) | Safe formatted output to buffer with size limit. ALWAYS use this. |
scanf(fmt, ...) | Formatted input from stdin. Avoid in production (buffer risks). |
sscanf(str, fmt, ...) | Parse formatted data from a string. |
| Function | Purpose |
|---|---|
malloc / calloc / realloc / free | Dynamic heap memory management. |
atoi / strtol / strtod | String-to-number conversion. |
rand() / srand(seed) | Pseudo-random number generation (use arc4random on modern systems). |
abs(n) / labs(n) / llabs(n) | Absolute value for int / long / long long. |
qsort(arr, n, size, cmp) | Generic quicksort โ sorts any array using a comparator function. |
bsearch(key, arr, n, size, cmp) | Binary search in sorted array. |
system(cmd) | Run shell command. UNSAFE in security-sensitive code. |
Math functions require linking with -lm: gcc app.c -lm -o app. All functions work on double by default; use sqrtf()/sinf() for float variants.
Key math.h Functions:
โข sqrt(x), cbrt(x) โ Square root, cube root.
โข pow(base, exp) โ Raise to power. Note: slower than manual multiplication for integer exponents.
โข sin(x), cos(x), tan(x) โ Trigonometric functions (argument in radians).
โข log(x), log2(x), log10(x) โ Natural/base-2/base-10 logarithms.
โข ceil(x), floor(x), round(x), fabs(x) โ Rounding and absolute value.
โข fmod(x, y) โ Floating-point modulo remainder.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char name[30]; int score; } Player;
/* Comparator: sort by score descending */
static int cmp_score_desc(const void *a, const void *b) {
const Player *pa = (const Player *)a;
const Player *pb = (const Player *)b;
return pb->score - pa->score; /* descending */
}
int main(void) {
Player players[] = {
{"Ravi", 850}, {"Anitha", 920},
{"Kiran", 760}, {"Priya", 990}
};
int n = sizeof(players) / sizeof(players[0]);
qsort(players, n, sizeof(Player), cmp_score_desc);
printf("=== Leaderboard ===\n");
for (int i = 0; i < n; i++) {
printf("#%d %-10s %d pts\n", i+1, players[i].name, players[i].score);
}
return 0;
}Q1: Why is sprintf() dangerous and what replaces it?
sprintf() has no buffer size limit and can overflow the destination string causing stack corruption. Always use snprintf(buf, sizeof(buf), fmt, ...); instead.
Q2: Why does math.h need -lm linker flag?
On Linux/glibc, math functions live in a separate libm.so library. The compiler does not link it automatically. GCC on macOS/Windows includes math in libc so -lm is optional there.
Q3: How do I generate random numbers in a range [min, max]?
Use min + rand() % (max - min + 1). For cryptographic randomness use /dev/urandom or arc4random_uniform() on BSD/macOS.
Q4: What is the comparator return value convention for qsort()?
Return negative if a should come before b, zero if equal, positive if b should come before a. Many implementations use a->field - b->field (watch for overflow with large integers!).
Q5: Can bsearch() find elements in an unsorted array?
No! bsearch() requires the array to be sorted by the same comparator used for searching. Calling it on unsorted data produces undefined results.