C

Lesson 01

Pointer ownership at boundaries

Make write ownership visible by receiving caller-owned buffers with size, instead of returning hidden shared storage.

Good Code

src/review_title.c
#include <stddef.h>
#include <string.h>

int copy_review_title(char *dst, size_t dst_size, const char *src)
{
    // Caller-owned storage makes the write target visible.
    if (dst == NULL || src == NULL || dst_size == 0) {
        return -1;
    }

    size_t length = 0;
    while (length < dst_size && src[length] != '\0') {
        length++;
    }

    if (length == dst_size) {
        return -1;
    }

    memcpy(dst, src, length + 1);
    return 0;
}

Bad Code

review_title.c
#include <string.h>

char *copy_review_title(char *src)
{
    // Returning shared static storage hides ownership across callers.
    static char title[64];
    strcpy(title, src);
    return title;
}

Review Notes

What to review

Good Code

The good version asks the caller to supply the destination buffer and its size. Reviewers can see where the write lands, how overflow is rejected, and how the error path returns.

Bad Code

The bad version returns a pointer to one shared static buffer. Two callers can overwrite each other, and the unchecked strcpy can write past the fixed array.

Takeaways

  • A C function that writes through a pointer should say who owns the storage and how large that storage is.