stdlib.h: Conversion, Allocation, Environment
This chapter covers <stdlib.h>: numeric conversion functions, memory allocation (malloc/calloc/realloc/free), and environment/utility functions. Allocation is introduced here and treated in depth in Part 4.
Why This Matters
<stdlib.h> is one of the most-used headers. Conversion functions (atoi, strtol, strtod) are the bridge between strings and numbers; allocation functions are the bridge to the heap; environment functions connect the program to the OS.
Prerequisites
c.stdlib.1— library overview.
Core Concept
Conversion functions
int atoi(const char *s); /* ASCII to int (no error detection) */
long strtol(const char *s, char **endp, int base);
double strtod(const char *s, char **endp);
strtol/strtod are the robust choices: they set *endp to the first unconverted character and report errors via errno and range checking.
Allocation functions
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
Covered in depth in c.memory.2.
Environment and utilities
void exit(int status);
void abort(void);
int system(const char *command); /* platform-dependent */
char *getenv(const char *name); /* not thread-safe in general */
int rand(void);
void srand(unsigned seed);
void qsort(void *base, size_t nmemb, size_t size,
int (*cmp)(const void *, const void *));
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size,
int (*cmp)(const void *, const void *));
Syntax
#include <stdlib.h>
long v = strtol(str, &end, 10);
int *p = malloc(sizeof *p);
qsort(arr, n, sizeof arr[0], compare);
Examples
Robust string-to-integer conversion
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main(void)
{
const char *s = " 123abc";
char *end = NULL;
errno = 0;
long v = strtol(s, &end, 10);
if (end == s) {
printf("no digits\n");
} else if (errno == ERANGE || v < INT_MIN || v > INT_MAX) {
printf("out of range\n");
} else {
printf("value %ld, rest: %s\n", v, end);
}
return 0;
}
Expected output: value 123, rest: abc.
qsort with a comparator
#include <stdlib.h>
int cmp_int(const void *a, const void *b)
{
const int *ia = a, *ib = b;
return (*ia > *ib) - (*ia < *ib);
}
int main(void)
{
int arr[] = {5, 2, 4, 1, 3};
qsort(arr, 5, sizeof arr[0], cmp_int);
return 0;
}
How It Works
Conversion functions parse the leading portion of a string, respecting optional whitespace and sign, and return the numeric value. Allocation functions obtain heap memory from the runtime. qsort sorts an array using the comparator; it is not stable and its performance is implementation-defined (usually introsort or quicksort).
Variations
atoi vs. strtol
atoi has no error detection (overflow is UB/undefined); strtol reports errors. Prefer strtol/strtod.
realloc semantics
realloc may move the block, invalidating the old pointer. If it fails, it returns NULL but leaves the original block intact. Never do p = realloc(p, n) directly — that leaks the original on failure.
Common Mistakes
- Using
atoifor untrusted input. p = realloc(p, n)(leaks on failure).- Forgetting to check allocation failure.
- Assuming
getenvis thread-safe or modifiable. - Using
randfor security (use a secure random source,c.sec.6).
Undefined Behavior
- Passing an invalid pointer to
free/realloc.VERIFIED - Using
reallocon a pointer not frommalloc/calloc/realloc(or NULL). - Overflow in
atoican be UB (undefined behavior, unlikestrtolwhich sets
errno).
Portability
atoi,strtol,strtod,malloc,free,qsort,bsearchare standard.systembehavior is implementation-defined.randquality is implementation-defined and generally poor.
Under the Hood
strtol/strtod parse digit by digit, accumulating value while checking for overflow. Allocation functions call the C runtime allocator, which typically manages the heap with free lists and may call the OS for more memory (c.memory.5).
Practical Usage
- Use
strtol/strtodfor all string-to-number parsing of untrusted input. - Check allocation results and handle
realloccorrectly. - Use
qsortfor general-purpose sorting; write a correct comparator.
Exercises
1. Write a robust integer parser using strtol that handles leading spaces, signs, and trailing garbage. 2. Demonstrate the p = realloc(p, n) leak and the correct pattern. 3. Use qsort and bsearch together on an array. 4. Explain why atoi("99999999999999999999") is not safe.
Deep Challenge
Implement a parse_int function that converts a decimal string to an int with full error reporting (overflow, no digits, trailing garbage), without using atoi and without invoking undefined behavior. Explain each check.
Related Concepts
c.memory.2— allocation in depth.c.core.24— void* and qsort comparators.c.sec.6— secure random generation.
References
- ISO/IEC 9899:2018 §7.22 (stdlib.h).
Verification
strtol/strtoderror reporting via end pointer and errno.VERIFIEDreallocfailure leaves original block intact.VERIFIEDqsortis not stable.VERIFIED- No example was executed during generation unless noted. `Execution not
verified.`
Progress
- [ ] Read
- [ ] Understand
- [ ] Complete examples
- [ ] Complete exercises
- [ ] Complete deep challenge
Concept checkboxes
- [ ] atoi/strtol/strtod
- [ ] malloc/calloc/realloc/free
- [ ] qsort/bsearch
- [ ] exit/abort/system/getenv
Mastery levels
| Concept | Current level (0–8) | Target level |
|---|---|---|
| c.lib.stdlib | 0 | 6 |