The snippet library.
Small, practical examples. Search by task or narrow things down below.
Allocate a zeroed array
Check calloc, use the allocation, and release it in C.
C✓ Tested
Allocate an independent copy of a C string
C: Include one extra byte for the terminating null character.
C✓ Tested
Allocate and free a typed array
C: Use sizeof on the pointed-to type and check allocation success before writing.
C✓ Tested
Allocate and initialize a structure
C: Use a compound literal assignment to initialize all ordinary structure fields.
C✓ Tested
Append text only when the destination has enough capacity
C: Check the combined lengths including the terminator before using strcat.
C✓ Tested
Append text to a file
Use append mode in C without replacing the existing file.
C✓ Tested
Calculate a cumulative sum for each position
C: Keep a running total and store each prefix result in a separate output array.
C✓ Tested
Calculate a fixed-window moving average
C: For this small window, sum each complete group and skip incomplete prefixes.
C✓ Tested
Calculate a least common multiple using a GCD
C: Divide before multiplying to reduce the risk of intermediate overflow.
C✓ Tested
Calculate a page count without an overflowing addition
C: Divide first and add one only when a nonzero remainder remains.
C✓ Tested
Calculate a simple total
C: Multiply a unit price by a quantity, then add a delivery fee.
C✓ Tested
Calculate a small factorial iteratively
C: Multiply a bounded sequence using an unsigned accumulator.
C✓ Tested