Search Knowledge

© 2026 LIBREUNI PROJECT

C Programming Mastery / Advanced Features

The Standard Library (libc) Utilities

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 *));

Works on sorted arrays to find an element in time.

Process Control and Termination

  1. exit(status): Terminates the program normally. A status of 0 indicates success.
  2. abort(): Terminates the program abnormally (often generates a core dump for debugging).
  3. 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 with time(NULL).

Note: rand() is not cryptographically secure. For security applications, use OS-specific APIs like /dev/urandom or BCryptGenRandom.

Interactive Lab

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), );
Runtime Environment

Interactive Lab

1#include <stdio.h>
2#include <stdlib.h>
3#include <time.h>
4 
5int main() {
6 srand(time(NULL));
7 printf("Random Roll (1-6): %d\n", (rand() % 6) + 1);
8 return 0;
9}
System Console

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.