courses Memory: who owns what 1/5

The Leaky Logger

A function allocates, nobody frees. Find the owner and make the junior release the buffer in the right place.

Lesson

The idea: every malloc has an owner

In C nobody frees memory for you. For every block you allocate, one piece of code is responsible for calling free exactly once. That piece of code is the owner.

A comment in a header often tells you who the owner is. Read it: "The CALLER owns the result."

The situation

make_greeting allocates a string and hands it out. log_greeting uses it, prints it, and returns. The test calls log_greeting a hundred times.

Your mission

Find the owner, then tell the junior which function must call free, on which variable, and where. "Fix the leak" is not an instruction. It is a wish.

What to watch for

  • A vague request makes the junior reach for the nearest trick. Check what it did before you trust it.
  • Freeing in the wrong function is worse than not freeing: it turns a leak into a crash.
  • Some tests are hidden. They check the cases you did not think about.

Try this exercise

Create a free account to tell the AI junior what to change, run the tests and the memory checker, and earn a completion code you can verify.

Starting code
greeter.c
#include "greeter.h"#include <stdlib.h>#include <string.h> char *make_greeting(const char *name) {    size_t n = strlen("Hello, !") + strlen(name) + 1;    char *s = malloc(n);    if (!s) return NULL;    snprintf(s, n, "Hello, %s!", name);    return s;} int log_greeting(FILE *out, const char *name) {    char *g = make_greeting(name);    if (!g) return -1;    int len = fprintf(out, "%s\n", g);    return len;}
greeter.h
#ifndef GREETER_H#define GREETER_H#include <stdio.h> /* Builds "Hello, <name>!" in a new heap buffer. The CALLER owns the result. */char *make_greeting(const char *name); /* Writes "Hello, <name>!\n" to `out`. Returns characters written, or -1. */int log_greeting(FILE *out, const char *name);#endif