C

Lesson 05

Struct ownership and borrowed views

Use small view structs to state borrowed data and lengths, instead of returning pointers to temporary storage.

Good Code

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

struct ReviewView {
    const char *title;
    size_t title_len;
};

struct ReviewView review_view_from_title(const char *title)
{
    // A view stores borrowed data plus its length.
    return (struct ReviewView) {
        .title = title,
        .title_len = strlen(title),
    };
}

Bad Code

review_view.c
#include <string.h>

struct ReviewView {
    char *title;
};

struct ReviewView default_review_view(void)
{
    char title[32];
    strcpy(title, "Draft review");

    // Returning stack storage breaks after the function returns.
    return (struct ReviewView) { .title = title };
}

Review Notes

What to review

Good Code

The good version returns a borrowed view: it keeps the caller-owned pointer and records the length. The const field tells readers that the view will not edit the title.

Bad Code

The bad version stores a pointer to a local stack array. The pointer becomes invalid as soon as the function returns, so later reads have undefined behavior.

Takeaways

  • A struct that borrows memory should say so through const pointers and lengths, while stack storage must never escape its function.