Chapter 27Intermediate

C stdlib.h Library Reference

Complete reference for stdlib.h - memory allocation, string conversion, random numbers, sorting, and program control.

20 min readUpdated 2024-12-16
stdlib.hmallocfreeatoirandqsortexit

What You Will Learn

  • Use memory functions (malloc, free)
  • Convert strings to numbers
  • Generate random numbers
  • Sort and search arrays

01Introduction to stdlib.h

📚 What is stdlib.h?

<stdlib.h> (Standard Library) provides essential utilities: memory allocation, type conversions, random numbers, sorting, and program control.

📋 Key Functions Overview

CategoryFunctions
Memorymalloc, calloc, realloc, free
Conversionatoi, atof, atol, strtol, strtod
Randomrand, srand
Sort/Searchqsort, bsearch
Programexit, abort, atexit, system
Mathabs, labs, div, ldiv

02Memory Allocation Functions

malloc() - Allocate Memory

void *malloc(size_t size);
size: Number of bytes to allocate
Returns: Pointer to allocated memory, or NULL
main.c
C
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Allocation failed!\n");
return 1;
}
// Memory is UNINITIALIZED (garbage values)

calloc() - Allocate and Zero-Initialize

void *calloc(size_t num, size_t size);
num: Number of elements
size: Size of each element
main.c
C
int *arr = (int *)calloc(5, sizeof(int));
// Memory is ZERO-INITIALIZED (all elements = 0)
printf("%d\n", arr[0]); // Output: 0

realloc() - Resize Memory

void *realloc(void *ptr, size_t new_size);
ptr: Pointer to existing memory
new_size: New size in bytes
main.c
C
int *arr = malloc(5 * sizeof(int));
// Need more space? Resize!
int *temp = realloc(arr, 10 * sizeof(int));
if (temp != NULL) {
arr = temp; // Safe pattern
}

free() - Deallocate Memory

void free(void *ptr);
main.c
C
int *arr = malloc(5 * sizeof(int));
// Use the memory...
free(arr); // Release memory
arr = NULL; // Prevent dangling pointer

03String Conversion Functions

FunctionPrototypeDescription
atoi()int atoi(const char *str)String → int
atof()double atof(const char *str)String → double
atol()long atol(const char *str)String → long
strtol()long strtol(const char *str, char **end, int base)String → long (with base)
strtod()double strtod(const char *str, char **end)String → double (safer)
conversions.c
C
1#include <stdlib.h>
2#include <stdio.h>
3
4int main() {
5 // Basic conversions
6 int num = atoi("42"); // 42
7 double pi = atof("3.14159"); // 3.14159
8 long big = atol("1000000"); // 1000000
9
10 // strtol with base (hex, binary, etc.)
11 char *end;
12 long hex = strtol("FF", &end, 16); // 255 (hex)
13 long bin = strtol("1010", &end, 2); // 10 (binary)
14 long dec = strtol("123abc", &end, 10); // 123, end points to "abc"
15
16 printf("Hex FF = %ld\n", hex);
17 printf("Binary 1010 = %ld\n", bin);
18
19 return 0;
20}

💡 strtol() vs atoi()

Use strtol() for better error handling — it tells you where parsing stopped and supports different bases (2, 8, 10, 16).

04Random Number Functions

rand()

int rand(void);

Returns pseudo-random number (0 to RAND_MAX)

srand()

void srand(unsigned int seed);

Seeds the random number generator

random.c
C
1#include <stdlib.h>
2#include <stdio.h>
3#include <time.h>
4
5int main() {
6 // Seed with current time (do once at program start!)
7 srand(time(NULL));
8
9 // Random number 0 to RAND_MAX
10 int r1 = rand();
11
12 // Random 0-99
13 int r2 = rand() % 100;
14
15 // Random 1-6 (dice roll)
16 int dice = (rand() % 6) + 1;
17
18 // Random 10-50
19 int r3 = (rand() % 41) + 10;
20
21 printf("Dice: %d\n", dice);
22 printf("Range 10-50: %d\n", r3);
23
24 return 0;
25}

⚠️ Important

Call srand() only once at program start. Calling it repeatedly with same seed produces same sequence!

06Program Control Functions

FunctionPrototypeDescription
exit()void exit(int status)Terminate program normally
abort()void abort(void)Terminate abnormally
atexit()int atexit(void (*func)(void))Register exit handler
system()int system(const char *cmd)Execute shell command
getenv()char *getenv(const char *name)Get environment variable
program_control.c
C
1#include <stdlib.h>
2#include <stdio.h>
3
4void cleanup() {
5 printf("Cleanup called!\n");
6}
7
8int main() {
9 // Register cleanup function
10 atexit(cleanup);
11
12 // Get environment variable
13 char *path = getenv("PATH");
14 printf("PATH: %.50s...\n", path);
15
16 // Execute system command
17 system("echo Hello from shell!");
18
19 // Normal exit (calls atexit handlers)
20 exit(EXIT_SUCCESS); // or exit(0)
21
22 // Never reached
23 return 0;
24}

07Integer Math Functions

FunctionPrototypeDescription
abs()int abs(int n)Absolute value of int
labs()long labs(long n)Absolute value of long
div()div_t div(int num, int den)Quotient and remainder
ldiv()ldiv_t ldiv(long num, long den)Long quotient and remainder
main.c
C
int x = abs(-42); // 42
long y = labs(-100000L); // 100000
div_t result = div(17, 5);
printf("17 / 5 = %d remainder %d\n", result.quot, result.rem);
// Output: 17 / 5 = 3 remainder 2

08Summary

🎯 Key Functions

Memory:

malloc, calloc, realloc, free

Conversion:

atoi, atof, strtol, strtod

Random:

rand, srand

Program:

exit, abort, system, getenv

09Next Steps

Learn about string manipulation functions: