Unit 4 · Lesson 322 minAcademic review pending

Use the standard library as a toolbox

Find declarations in standard headers and use common character, math, conversion, memory, and utility functions correctly.

Choose explanation

After this lesson

You should be able to

  • Connect a standard function with its header and contract.
  • Prefer checked conversion functions over silent assumptions.
01

Headers declare; libraries define

A standard header exposes declarations, types, and macros. stdio.h covers streams, string.h covers byte strings and memory blocks, ctype.h classifies characters, stdlib.h includes conversions and allocation, and math.h provides mathematical functions.

Include the correct header so the compiler can check calls. Read the contract: accepted input, return value, error signal, and side effects. A familiar name is not a substitute for knowing those rules.

02

Conversion must detect leftovers

atoi cannot report detailed failure, so strtol is preferable for checked integer parsing. It reports where conversion stopped and can signal range errors through errno.

Character-classification functions such as isdigit accept either EOF or an unsigned-char value converted to int. Cast a possibly signed char to unsigned char before passing it.

Checked whole-number parse
char *end;
errno = 0;
long value = strtol(text, &end, 10);

if (errno == ERANGE || end == text || *end != '\0') {
    fprintf(stderr, "Invalid integer\n");
}

Try it yourself

Which headers declare strlen, sqrt, and malloc?

Need a hint?

Think strings, mathematics, and general utilities.

Check the worked solution

strlen: string.h; sqrt: math.h; malloc: stdlib.h.

Quick check

Why is strtol generally safer than atoi for external input?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

C standard functions · Libraries

Maps to course outcomes CO3, CO4.