TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › C Buffers, Lengths and Unsafe Functions

C Buffers, Lengths and Unsafe Functions

C gives you a block of memory and trusts you to stay inside it. A char buf[8] is eight bytes on the stack and nothing else: no length stored with it, no check when you write the ninth byte. Functions such as strcpy, strcat, sprintf and gets copy until the source ends, whatever the destination size, and the bytes that do not fit overwrite whatever lies next in memory: other variables, the saved frame pointer, the return address. Out-of-bounds writes (CWE-787) were first in MITRE's CWE Top 25 from 2021 to 2023, second in 2024 and fifth in 2025. You do not need to write C to work in security, but you need to recognise these patterns in a patch, a crash report or a code review. C itself is taught in C; the memory layout behind it is in Memory Protection, and exploitation is a concept for the later memory-safety course.

Definitions

  • Buffer: a fixed-size array. Its size is known only to the code that declared it, and is lost when it decays to a pointer (char *).
  • C string: bytes ending in a NUL ('\0'). strlen counts the bytes before the NUL, so a string of length n needs n + 1 bytes.
  • Off-by-one: allocating or checking n where n + 1 was needed (or <= where < was meant).
  • Unsafe functions: gets (removed in C11), strcpy, strcat, sprintf, scanf("%s") with no width. Bounded replacements: fgets, snprintf, strlcpy/strlcat (BSD, glibc 2.38+), memcpy with a checked length.
  • AddressSanitizer (ASan): a compiler option (-fsanitize=address) that puts poisoned "red zones" around every object and stops the program at the first bad access, with a report.
  • _FORTIFY_SOURCE: glibc checks, enabled at -O1 and above on Ubuntu, that replace some calls with versions that know the destination size and abort on overflow.

Bounded copies done right

strncpy looks safe but has a trap: when the source is too long it fills the buffer and does not write a NUL. snprintf always terminates (for a size above 0) and returns the length it wanted to write, so truncation can be detected.

c · try it yourself
#include <stdio.h>
#include <string.h>

/* Copy src into dst of size dstsz. Returns 1 if it fit, 0 if it was truncated. */
static int copy_checked(char *dst, size_t dstsz, const char *src) {
    int n = snprintf(dst, dstsz, "%s", src);
    return n >= 0 && (size_t)n < dstsz;
}

int main(void) {
    char buf[8];
    const char *names[] = {"alice", "bob-the-builder", "1234567", "12345678"};

    strncpy(buf, "bob-the-builder", sizeof buf);
    printf("strncpy: last byte is %s\n", buf[sizeof buf - 1] == '\0' ? "NUL" : "NOT NUL (unterminated!)");

    for (int i = 0; i < 4; i++) {
        int ok = copy_checked(buf, sizeof buf, names[i]);
        printf("%-16s len %2zu -> \"%s\" %s\n", names[i], strlen(names[i]), buf, ok ? "ok" : "TRUNCATED");
    }
    return 0;
}
strncpy: last byte is NOT NUL (unterminated!)
alice            len  5 -> "alice" ok
bob-the-builder  len 15 -> "bob-the" TRUNCATED
1234567          len  7 -> "1234567" ok
12345678         len  8 -> "1234567" TRUNCATED

"1234567" (7 characters) fits in 8 bytes with its NUL; "12345678" (8 characters) does not, which is exactly the off-by-one boundary. A tool that silently truncates a user name may compare the wrong user, so the caller must act on the TRUNCATED result: reject the input, not use the shortened copy.

The overflow, caught by AddressSanitizer

The session compiles two classic bugs in a toy program: a heap allocation that forgot the NUL byte, and an unchecked strcpy into a stack buffer. It runs in your sandbox; the sanitizer stops each program at its first invalid write. Addresses in the reports change from run to run and are masked when the session is verified.

bash · try it yourself
cat > bugs.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *dup_name(const char *s) {
    char *p = malloc(strlen(s));          /* BUG: no room for the NUL */
    strcpy(p, s);
    return p;
}

void greet(const char *name) {
    char buf[8];
    strcpy(buf, name);                    /* BUG: no length check */
    printf("hi %s\n", buf);
}

int main(int argc, char **argv) {
    if (argv[1][0] == 'h') { char *n = dup_name("alice"); puts(n); free(n); }
    else greet("a-name-that-is-too-long");
    return 0;
}
SRC
gcc -g -O0 -fsanitize=address,undefined bugs.c -o bugs
echo "== heap: malloc(strlen(s))"
./bugs h 2>&1 | grep -E 'ERROR|WRITE|READ|#[0-2] |located' | sed -n '1,6p'
echo "== stack: strcpy into char buf[8]"
./bugs s 2>&1 | grep -E 'ERROR|WRITE|#[0-2] |located' | sed -n '1,6p'
echo "== the same stack bug, built -O2 without ASan (glibc FORTIFY)"
gcc -O2 bugs.c -o bugs-o2 2>/dev/null
./bugs-o2 s 2>&1 | cat; echo "exit code: ${PIPESTATUS[0]}"
== heap: malloc(strlen(s))
==15==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000015 at pc 0x7e3bae833923 bp 0x7ffefa660650 sp 0x7ffefa65fdf8
WRITE of size 6 at 0x502000000015 thread T0
    #0 0x7e3bae833922 in strcpy ../../../../src/libsanitizer/asan/asan_interceptors.cpp:563
    #1 0x5b687da903c5 in dup_name /home/learner/bugs.c:7
    #2 0x5b687da905e2 in main /home/learner/bugs.c:18
0x502000000015 is located 0 bytes after 5-byte region [0x502000000010,0x502000000015)
== stack: strcpy into char buf[8]
==18==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7f0110100028 at pc 0x7f0112f55923 bp 0x7fff32a56210 sp 0x7fff32a559b8
WRITE of size 24 at 0x7f0110100028 thread T0
    #0 0x7f0112f55922 in strcpy ../../../../src/libsanitizer/asan/asan_interceptors.cpp:563
    #1 0x624a2ed60488 in greet /home/learner/bugs.c:13
    #2 0x624a2ed60625 in main /home/learner/bugs.c:19
Address 0x7f0110100028 is located in stack of thread T0 at offset 40 in frame
== the same stack bug, built -O2 without ASan (glibc FORTIFY)
*** buffer overflow detected ***: terminated
exit code: 134

Read the reports from the top: the kind of error (heap-buffer-overflow, stack-buffer-overflow), the size of the bad access, and the stack trace with file and line, here bugs.c:7 (the strcpy in dup_name) and bugs.c:13. The heap report also says the 6-byte write hit a region of 5 bytes: "alice" plus its NUL into malloc(5). Without ASan, the optimised build is still stopped by FORTIFY (*** buffer overflow detected ***, exit 134 from SIGABRT), because the compiler knew buf has 8 bytes. A pointer of unknown size gets no such protection.

What the stack bug would overwrite without those checks is easier to see in the stack-frame lab. "a-name-that-is-too-long" is 23 characters plus the NUL, so strcpy writes 24 bytes into char buf[8]. With ASan redzones on, the lab stops at the first byte past the buffer, as the report did. Turn ASan off and the stack canary and saved rbp are overwritten and the canary check aborts at return; turn the canary off too and the 24 bytes reach the return address.

offsetbytes, address →contents (rows grow ↑)rbp+0x40rbp+0x38rbp+0x30rbp+0x28rbp+0x20rbp+0x18rbp+0x10caller's frame (main)rbp+0x08ret → main+0x2arbp+0x00saved rbp → caller framerbp−0x08stack canary (random)rbp−0x10rbp−0x18rbp−0x20rbp−0x28✕ASan redzone (poisoned)rbp−0x30AAAAAAAAchar buf[8]void greet(int fd) {char buf[8];read(fd, buf, 24);}✕ copy input– check canary– leave (pop rbp)– retcaught: ASanASan:stack-buffer-overflowon the write of byte 9(buf[8], one past theend); abortabstract model: placeholder values, only 'A' (0x41) bytes are written

How these bugs are detected

  • Compiler warnings: -Wall -Wextra -Wformat-security -Wstringop-overflow catch many constant-size cases at compile time.
  • Sanitizers in tests and fuzzing: build with -fsanitize=address,undefined and run the test suite and a fuzzer; every out-of-bounds access becomes a report like the ones above.
  • Code review of every strcpy, strcat, sprintf, gets, scanf("%s"), memcpy(dst, src, n) where n comes from the input, and malloc(strlen(x)) without + 1. Tools: grep, Semgrep, CodeQL, flawfinder.
  • In production: crashes in strcpy/memcpy frames, *** buffer overflow detected *** and stack smashing detected (the stack canary) in logs are signs of a bug, possibly under attack.

How they are fixed

  1. Carry the size with the buffer and pass both: f(char *dst, size_t dstsz, …).
  2. Use bounded functions and check the result: snprintf (compare its return value with the size), fgets, strlcpy; never gets.
  3. Allocate len + 1 for strings, and check malloc's result for NULL.
  4. Compile with hardening in release builds: -O2 -D_FORTIFY_SOURCE=3 -fstack-protector-strong -fPIE -pie -Wl,-z,relro,-z,now. These do not fix bugs; they make them harder to exploit (Memory Protection).
  5. Prefer a memory-safe language for new code that parses untrusted input: Go and Rust, or C++ with std::string and .at().

Pitfalls

  • sizeof on a pointer gives 8 (on 64-bit), not the buffer size: inside a function that received char *buf, sizeof buf is wrong.
  • strncat(dst, src, n): n is the maximum number of bytes to append, not the size of dst. The correct bound is dstsz - strlen(dst) - 1.
  • Silent truncation can be a vulnerability too: a path or a user name cut at the buffer size may name something else.
  • ASan is for testing. It slows programs down by about 2x and changes memory layout; don't ship it.

Practice

1. What is wrong with char out[16]; sprintf(out, "user=%s", name); and how do you fix it?

sprintf writes 5 + strlen(name) + 1 bytes regardless of out's size, so a name of 11 or more characters overflows. Fix: int n = snprintf(out, sizeof out, "user=%s", name); if (n < 0 || (size_t)n >= sizeof out) { /* reject */ }.

2. A patch changes if (len > sizeof(buf)) to if (len >= sizeof(buf)) before memcpy(buf, src, len); buf[len] = 0;. Why?

With len == sizeof(buf) the old check passed, memcpy filled the buffer exactly, and buf[len] = 0 wrote one byte past the end: an off-by-one. The new check leaves room for the NUL.

3. In the ASan heap report, why is the write 6 bytes and the region 5 bytes?

strcpy copies "alice" and its terminating NUL, 6 bytes, into malloc(strlen("alice")), which is 5 bytes.

Test yourself

Why is strncpy(buf, src, sizeof buf) not a complete fix for strcpy?

  1. It is slower
  2. When src is too long it fills buf without a terminating NUL
  3. It only works on the heap
  4. It copies nothing

How many bytes does the string "12345678" need in a C buffer?

  1. 7
  2. 8
  3. 9
  4. 16

In an AddressSanitizer report, which line tells you where the bug is?

  1. The shadow-byte map
  2. The first stack frames (#0, #1) with file and line
  3. The exit code
  4. The BuildId

What did the -O2 build without ASan print for the stack overflow?

  1. Nothing; it ran normally
  2. *** buffer overflow detected ***: terminated (glibc FORTIFY)
  3. Segmentation fault only
  4. An ASan report

In the stack-frame lab, 24 bytes go into char buf[8] with ASan off and the canary on. What is overwritten?

  1. Nothing outside buf
  2. The canary and the saved rbp, so the canary check aborts at return
  3. Only the return address
  4. The caller's frame only