upgrade
upgrade

🧑🏽‍💻Intro to C Programming

Common C Library Functions

Study smarter with Fiveable

Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.

Get Started

Why This Matters

The C standard library is your toolkit for solving real programming problems efficiently. When you're writing C code, you're not expected to reinvent the wheel—these functions handle the heavy lifting for input/output operations, memory management, string manipulation, and file handling. Understanding how they work under the hood is what separates programmers who write functional code from those who write reliable, secure code.

You're being tested on more than just syntax. Exams will ask you to identify memory safety issues, buffer overflow risks, proper resource cleanup, and function return values. Don't just memorize function names—know what category each function belongs to, what can go wrong when using it, and how it interacts with memory. That conceptual understanding is what earns you points on FRQs.


Input/Output Functions

These functions handle communication between your program and the outside world—the console, specifically. They use format specifiers to translate between C data types and human-readable text.

printf()

  • Outputs formatted text to stdout—the primary tool for displaying results and debugging your programs
  • Format specifiers like %d (integers), %f (floats), %s (strings), and %c (characters) control how data appears
  • Returns the number of characters printed—useful for error checking, though often ignored in practice

scanf()

  • Reads formatted input from stdin—stores values directly into memory locations you specify with pointers
  • Requires the address-of operator (&) for non-pointer variables; forgetting this causes undefined behavior
  • Whitespace handling varies by specifier%s stops at whitespace, %c reads it, which trips up many students

Compare: printf() vs. scanf()—both use format specifiers, but scanf() requires pointers to store input while printf() takes values directly. If an FRQ asks about input validation, remember that scanf() returns the number of successfully matched items—always check this return value.


String Manipulation Functions

String functions operate on null-terminated character arrays. The null terminator (\0) marks where the string ends, and these functions rely on it completely.

strlen()

  • Returns the length of a string—counts characters up to but not including the null terminator
  • Traverses the entire string to count, making it O(n)O(n) time complexity
  • Essential for bounds checking—use it before copying or concatenating to prevent buffer overflows

strcpy()

  • Copies source string to destination—includes the null terminator in the copy
  • No bounds checking built in—the destination buffer must be large enough, or you risk a buffer overflow
  • Use strncpy() for safer copying—it accepts a maximum length parameter to limit characters copied

strcat()

  • Appends source string to the end of destination—overwrites the destination's null terminator and adds a new one
  • Destination must have enough space for both strings plus the null terminator
  • Common bug source—forgetting to allocate space for the combined length plus one

strcmp()

  • Compares two strings lexicographically—returns 0 if equal, negative if first < second, positive if first > second
  • Case-sensitive comparison"Apple" and "apple" are not equal; use strcasecmp() for case-insensitive
  • Compares character by character using ASCII values until a difference is found or both reach \0

Compare: strcpy() vs. strcat()—both modify the destination buffer and risk overflow, but strcpy() overwrites from the beginning while strcat() appends to the end. Both have safer n-limited versions (strncpy(), strncat()).


Dynamic Memory Management

These functions let you allocate and free memory at runtime from the heap. Unlike stack variables, heap memory persists until you explicitly release it.

malloc()

  • Allocates a block of memory of the specified size in bytes and returns a pointer to it
  • Returns NULL if allocation fails—always check before using the pointer to avoid crashes
  • Memory is uninitialized—contains garbage values; use calloc() if you need zero-initialized memory

free()

  • Deallocates memory previously allocated by malloc(), calloc(), or realloc()
  • Prevents memory leaks—every malloc() should have a corresponding free() when you're done
  • Double-free is undefined behavior—freeing the same pointer twice can corrupt memory or crash your program

Compare: malloc() vs. free()—they're a matched pair for memory lifecycle management. A common exam question: what happens if you malloc() without free()? Memory leak. What if you free() without malloc()? Undefined behavior. Always pair them correctly.


File I/O Functions

File functions work through file pointers (FILE *). The operating system manages the actual file; your program interacts through this pointer abstraction.

fopen()

  • Opens a file and returns a FILE * pointer—modes include "r" (read), "w" (write/create), "a" (append)
  • Returns NULL if the file can't be opened—always check before proceeding with file operations
  • Write mode truncates existing files—use "a" to append instead of overwriting

fclose()

  • Closes the file and flushes buffers—ensures all pending writes are completed before releasing resources
  • Returns 0 on success, EOF on failure—though errors on close are rare, they can indicate data loss
  • Essential for resource cleanup—open files consume system resources; always close when done

fread()

  • Reads binary data from a file into a buffer—syntax: fread(buffer, element_size, count, file_pointer)
  • Returns the number of elements successfully read—may be less than requested if EOF is reached
  • Ideal for structured data—reading arrays or structs in a single call is more efficient than character-by-character

fwrite()

  • Writes binary data from a buffer to a file—syntax mirrors fread() with same parameter order
  • Returns the number of elements written—compare to requested count to detect write errors
  • Data is not human-readable—binary files are compact but require matching fread() to interpret

Compare: fread() vs. fwrite()—identical parameter structure but opposite data direction. Both return element count (not bytes), which is crucial for error checking. For text files, consider fprintf() and fscanf() instead.


Type Conversion Functions

These functions convert strings to numeric types. They parse character sequences and return the equivalent numeric value.

atoi()

  • Converts a string to an int—parses digits after skipping leading whitespace
  • No error detection—returns 0 for both "0" and "hello", making failures invisible
  • Use strtol() for robust code—it provides error checking and handles different bases

atof()

  • Converts a string to a double—handles decimal points and scientific notation
  • Same limitations as atoi()—no way to distinguish between "0.0" and invalid input
  • Returns 0.0 on failure—consider strtod() when you need to validate user input

Compare: atoi() vs. atof()—same parsing behavior for different types, same lack of error handling. Exams may ask why these are considered unsafe—the answer is their silent failure mode. Modern code prefers strtol() and strtod().


Random Number Generation

rand()

  • Generates a pseudo-random integer between 0 and RAND_MAX (typically 32767 or higher)
  • Deterministic without seeding—same sequence every run unless you call srand() first
  • Seed with srand(time(NULL)) for different sequences each program execution—common exam pattern

Quick Reference Table

ConceptBest Examples
Console I/Oprintf(), scanf()
String Length/Comparisonstrlen(), strcmp()
String Modificationstrcpy(), strcat()
Dynamic Memorymalloc(), free()
File Accessfopen(), fclose()
Binary File I/Ofread(), fwrite()
String-to-Numberatoi(), atof()
Randomizationrand(), srand()

Self-Check Questions

  1. Which two string functions share the risk of buffer overflow if the destination isn't large enough, and what safer alternatives exist for each?

  2. What does malloc() return if memory allocation fails, and why is checking this return value critical before using the pointer?

  3. Compare printf() and scanf() in terms of how they use format specifiers—what's the key difference in how arguments are passed?

  4. If strcmp("apple", "banana") returns a negative value, what does that tell you about the comparison, and why?

  5. A student's program produces the same "random" numbers every time it runs. What function call are they missing, and what argument should they pass to it?