Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 135 ยท Standard Library

Useful stdlib.h Functions

Tour the most useful functions in C's stdlib.h - exit, EXIT_SUCCESS, atexit, abort and _Exit, abs and div, getenv, and strtol and strtod for safe number parsing.

<stdlib.h> is the "general utilities" header of C, a bit of a grab bag. You've already used several of its residents: malloc and free in Dynamic Memory, rand in Random Numbers, and qsort and bsearch in the previous lesson. This lesson covers the rest of the functions you'll reach for regularly.

They fall into four groups: ending a program (exit, atexit, abort, _Exit, quick_exit), integer arithmetic helpers (abs, labs, llabs, div), talking to the environment (getenv, system), and converting strings to numbers (strtol, strtoul, strtod and the risky atoi). Knowing exactly what each one does, and what it doesn't, saves you from some surprisingly common bugs.

Ending a program: exit and the exit status

Returning from main ends the program, and the returned value becomes its exit status. exit(status) does the same thing from anywhere, even deep inside a helper function. The status tells whoever started the program (a shell, a script, a build system, a CI pipeline) whether it worked:

  • EXIT_SUCCESS (0) means success.
  • EXIT_FAILURE (1 on Linux, macOS and Windows) means failure.
  • Other small values (up to 255 on Unix-like systems) can encode specific errors; grep returns 1 for "no match" and 2 for "error", for example.

exit does an orderly shutdown: it calls the functions registered with atexit (in reverse order of registration), flushes and closes all open streams, so no buffered output is lost, removes files created by tmpfile, and then returns the status to the operating system.

C exit runs atexit handlers in reverse order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This program fails on purpose: check_config(-1) calls exit(EXIT_FAILURE), so the program ends with status 1 and never reaches the last puts. Before it ends, the two handlers run, the one registered last first: settings saved, then database closed. Returning from main triggers exactly the same handlers, because returning from main is equivalent to calling exit with the return value.

You can register at least 32 handlers. They're useful for cleanup that must happen however the program ends (flushing a log, removing a lock file), but they make control flow harder to follow, so in most programs the explicit cleanup at the end of main (or the goto cleanup pattern) is clearer.

Note: Don't use exit as a substitute for error handling inside reusable functions. A library function that calls exit takes the decision away from its caller, which might have wanted to retry, show a dialog or save the user's work. Return an error code, and let main decide when to exit.

The other ways out: abort, _Exit and quick_exit

Three more functions end a program, each skipping different parts of the orderly shutdown:

Function atexit handlers Flushes streams Typical use
exit(status) yes yes normal termination
quick_exit(status) (C11) only at_quick_exit handlers no fast exit when full cleanup could hang
_Exit(status) (C99) no not with glibc (implementation-defined) in a child process after fork, or a signal handler
abort() no not guaranteed "this can't happen": crash immediately, often with a core dump

abort raises the SIGABRT signal and ends the program with an "abnormal termination" status; assert calls it when a check fails (Predefined Macros and assert). The difference in flushing is easy to see, because output to a pipe or file is buffered until the buffer fills or the program flushes it:

C exit flushes buffered output, _Exit does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Here the printf line usually disappears: our editor collects output through a pipe, so stdout is fully buffered, and glibc's _Exit ends the process without flushing it. In a terminal, stdout is line-buffered, and the line would have been written at the \n already. Change _Exit to exit and both lines appear. fflush(stdout) before _Exit would also save the line.

Integer helpers: abs and div

abs, labs and llabs return the absolute value of an int, long and long long. For floating-point values use fabs from <math.h> (The Math Library).

The one trap: in two's complement, the most negative value has no positive counterpart. abs(INT_MIN) would need to return 2147483648, which doesn't fit in an int, so it's undefined behavior. Check for INT_MIN first, or convert to a wider or unsigned type before taking the magnitude.

div(numerator, denominator) computes the quotient and remainder in one call and returns them in a div_t struct with members quot and rem (ldiv, lldiv and imaxdiv in <inttypes.h> do the same for wider types). Since C99, integer division truncates toward zero, so div gives the same results as / and %:

C abs, div and splitting seconds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

div(-17, 5) gives quotient -3 and remainder -2, because the quotient is rounded toward zero and the remainder takes the sign of the numerator. 98765 seconds is 27h 26m 05s. The INT_MIN trick works because unsigned arithmetic wraps around modulo 232, which is well-defined: 0u - (unsigned)INT_MIN is 2147483648.

div was once faster than separate / and % on some machines; today compilers combine the two operations automatically, so use whichever reads better. Its real advantage is returning both results from one expression.

Environment variables: getenv

Every process inherits a set of environment variables, name=value strings such as PATH (where to look for programs), HOME (the user's home folder) or LANG (the preferred language). Programs use them for configuration that shouldn't be hard-coded: a log level, a database URL, a feature flag. getenv(name) returns a pointer to the value, or NULL if the variable isn't set.

C Reading environment variables with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Our sandbox runs programs with a very small environment: HOME is /tmp, PWD is the folder that holds main.c, and USER isn't set, so the program falls back to defaults. On your own machine you'd see your real home folder and username. Separating PATH at : works on Linux and macOS; Windows uses ;.

Three rules for getenv:

  • Always check for NULL. Passing NULL to printf("%s") or strcmp is undefined behavior; never assume a variable exists.
  • Don't modify or free the returned string. It belongs to the environment, and a later getenv call (or a setenv on POSIX) may overwrite it. Copy it if you need to keep it.
  • Treat it as untrusted input. Whoever starts your program controls the environment, so validate values just like user input.

Standard C can only read the environment. Setting variables uses POSIX setenv/unsetenv or Windows _putenv_s.

system: running a command

system(command) passes a command string to the operating system's shell and waits for it to finish:

C
int status = system("ls -l");    /* POSIX shell; "dir" on Windows */
if (status == -1) {
    perror("system");
}

It's handy for quick tools, but avoid it in real programs: it's slow (it starts a whole shell), its result is platform-specific, and building the command from user input invites command injection (a file name like x; rm -rf ~ becomes two commands). Use the platform's process APIs (fork/exec or posix_spawn on POSIX, CreateProcess on Windows) instead. In our sandbox, programs can't start other programs reliably, so there's no live demo here.

Converting strings to numbers: a recap

Converting Strings and Numbers covers this topic in depth; here's the essential summary of the <stdlib.h> functions:

Function Converts to Error detection
atoi, atol, atoll, atof int, long, long long, double none: garbage gives 0, overflow is UB
strtol, strtoll long, long long end pointer + errno == ERANGE
strtoul, strtoull unsigned long, unsigned long long same, but accepts a minus sign (see below)
strtod, strtof, strtold double, float, long double end pointer + errno == ERANGE

The strto* functions take a char **end argument that receives a pointer to the first character they didn't use, and integer versions take a base: 10 for decimal, 16 for hex, 2 for binary, or 0 to detect the base from the prefix like C source code does (0x1F is hex, 017 is octal).

C strtol, strtoul and strtod in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A few results deserve attention:

  • "017" with base 0 is octal 15. That's surprising for user input like ZIP codes or times ("08" stops at the 8 and gives 0), so use base 10 unless you specifically want prefixes.
  • "0b101" gives 0 here, and the rest is "b101". Binary prefixes in strtol with base 0 or 2 are new in C23 and need a C library that implements them (glibc 2.38 or later); our server's glibc is older, so it stops at the b. Don't rely on 0b input being accepted yet.
  • strtoul("-1") returns ULONG_MAX, 18446744073709551615 on our server, without any error: the standard says it negates the result in the unsigned type. If negative input is invalid, check for a '-' yourself.
  • 1e999 is too large for a double, so strtod returns infinity (inf) and sets ERANGE.
  • atoi has no error reporting at all, and overflowing input is undefined behavior. Prefer strtol everywhere outside quick experiments.

A few more residents

  • calloc, realloc, aligned_alloc (C11) and free: the rest of the memory family (Dynamic Memory). C23 adds free_sized and free_aligned_sized.
  • mblen, mbtowc, wctomb, mbstowcs, wcstombs: conversions between multibyte (for example UTF-8) and wide characters, which depend on the locale.
  • memalignment (C23): returns the alignment of a pointer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A program registers atexit(a) and then atexit(b), and later calls exit(0). In which order do the handlers run?

    Handlers run in the reverse order of registration, and they run for both exit and a normal return from main.
  2. 2. Which ending can lose output that printf has written but not yet flushed (with glibc)?

    exit (and returning from main) flushes all open streams. _Exit skips the atexit handlers, and glibc does not flush stdio buffers there.
  3. 3. What does div(-17, 5) return?

    Integer division truncates toward zero since C99, so the quotient is -3, and the remainder has the sign of the numerator, -2 (because -3 * 5 + -2 = -17).
  4. 4. getenv("APP_MODE") is called but the variable isn't set. What should your code expect?

    getenv returns NULL for variables that don't exist. Using that pointer as a string is undefined behavior, so check it and fall back to a default.
  5. 5. What does strtol("08", &end, 0) return?

    With base 0, a leading 0 means octal, and 8 isn't an octal digit, so only "0" is converted and end points at "8". Use base 10 for user input.

Summary

  • exit(status) ends the program from anywhere with an orderly shutdown: atexit handlers (in reverse order), then flushing and closing streams. Return EXIT_SUCCESS or EXIT_FAILURE so callers know what happened.
  • abort crashes immediately (used by assert), _Exit ends without handlers or (in glibc) flushing, and C11 quick_exit runs only at_quick_exit handlers.
  • abs, labs and llabs give integer absolute values (abs(INT_MIN) is undefined); div, ldiv and lldiv return quotient and remainder together, truncating toward zero.
  • getenv reads environment variables and returns NULL when one isn't set; don't modify its result, and validate the value. system runs a shell command but is slow and unsafe with user input.
  • Parse numbers with strtol, strtoul and strtod and check the end pointer and errno; base 0 detects 0x, 0 (octal) and, in C23, 0b prefixes. Avoid atoi for anything that matters.

Next: Command-Line Arguments, where you'll read argc and argv and parse options for your own tools.