Good Code
The good version exposes a constructor and a matching review_free. If title allocation fails, it releases the struct before returning failure.
Lesson 03
Pair heap allocation with a visible free function so callers know when they own memory and when to release it.
#include <stdlib.h>
#include <string.h>
struct Review {
char *title;
};
struct Review *review_create(const char *title)
{
struct Review *review = malloc(sizeof *review);
if (review == NULL) {
return NULL;
}
size_t length = strlen(title) + 1;
review->title = malloc(length);
if (review->title == NULL) {
free(review);
return NULL;
}
// The create/free pair states who owns heap memory.
memcpy(review->title, title, length);
return review;
}
void review_free(struct Review *review)
{
if (review != NULL) {
free(review->title);
free(review);
}
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *review_title_for_display(const char *title)
{
// Heap allocation without a matching owner leaks per call.
char *label = malloc(strlen(title) + 10);
sprintf(label, "Review: %s", title);
return label;
}The good version exposes a constructor and a matching review_free. If title allocation fails, it releases the struct before returning failure.
The bad version allocates a display label and returns it without naming who must free it. Call sites can leak memory or free the same pointer in inconsistent places.