The Role of libc
The C Standard Library (often referred to as libc) is a collection of headers and binaries that provide essential functionality. It is the bridge between your portable C code and the underlying Operating System.
Sorting and Searching
Instead of writing your own sort, C provides highly optimized generic algorithms.
qsort: The Generic Sorter
qsort can sort any array of any type. It uses a Comparison Callback to determine the order of elements.
void qsort(void *base, size_t nitems, size_t size,
int (*compar)(const void *, const void *));
bsearch: Binary Search
Works on sorted arrays to find an element in time.
Process Control and Termination
exit(status): Terminates the program normally. A status of0indicates success.abort(): Terminates the program abnormally (often generates a core dump for debugging).atexit(callback): Registers a function to be called automatically when the program exits. This is perfect for cleaning up resources or logging.
void cleanup() { printf("Cleaning up...\\n"); }
int main() {
atexit(cleanup);
return 0; // cleanup() is called automatically
}
String to Number Conversions
Avoid atoi—it has no error handling. Use the strto... family instead:
strtol: String to long.strtod: String to double.
These functions provide a pointer to the “first character that couldn’t be converted,” allowing you to detect malformed input.
Random Number Generation
rand(): Returns a pseudo-random integer.srand(seed): Seeds the random number generator. Usually seeded withtime(NULL).
Note: rand() is not cryptographically secure. For security applications, use OS-specific APIs like /dev/urandom or BCryptGenRandom.
Comparison Callbacks
int cmp(const void *a, const void *b) { return (*(int*)a - *(int*)b); } // To sort an array of 5 ints: qsort(arr, 5, sizeof(int), );
Interactive Lab
Waiting for signal...
Math and Limits
<math.h>:sin,cos,pow,sqrt,ceil,floor. Note: You often need to link with-lm.<limits.h>:INT_MAX,CHAR_BIT,LLONG_MIN. Use these to write portable code that doesn’t make assumptions about bit-widths.