bhylu.com

Advertisements

C Dynamic Structures

Build a small record whose cleanup function releases its nested allocation before the record.

How it works

A dynamically allocated structure may itself own other resources. Its cleanup contract must account for every level. Initialize pointer members to null values before fallible acquisition, then one cleanup helper can safely handle partial construction. Use sizeof on the pointed-to object rather than repeating a type name in an allocation. The helper below accepts null, releases the nested name if present, then releases the record. It does not leave external borrowed views valid after destruction.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror dynamic-records.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · dynamic-records.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Station { int id; char *name; };
static void destroy_station(struct Station *station) {
    if (station != NULL) {
        free(station->name);
        free(station);
    }
}

int main(void) {
    struct Station *station = malloc(sizeof *station);
    if (station == NULL) { return 1; }
    station->name = NULL;
    station->id = 4;
    station->name = malloc(6);
    if (station->name == NULL) { destroy_station(station); return 1; }
    memcpy(station->name, "Ridge", 6);
    printf("%d: %s\n", station->id, station->name);
    destroy_station(station);
    return 0;
}

Expected result

4: Ridge

The allocation failure branch can use the same destroy helper because the nested pointer already has a valid null value. A shallow structure copy would duplicate the name pointer and create two apparent owners, so this record must not be copied without an explicit deep-copy or ownership-transfer policy. An opaque module can hide these details from callers.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements