topskill.dev
CoursesTracks
All courses/C Programming for BeginnersWhere the storage comes from
Allocated Memory and Lifetime
1 / 8
← C Programming for Beginners
○What a program actually does○The computer and the operating system○From a C file to a running program○Compiled and interpreted programs○Trace One Tiny C Program○Print the Opening Sign✦Module Quiz
○Your First C Program○Variables and Formatted Output○Arithmetic and Integer Division○Formatting and Numeric Conversion○Calculate a Shop Total✦Module Quiz
○Declare and initialize variables○Label the parts bin○Assign a new value○Update the checkout board○Choose int, double, and char○Write a battery test label○Keep local names and constants clear○Count free kit slots✦Module Quiz
○Match printf placeholders and arguments○Print a radio test slip○Build lines with escapes and multiple calls○Print a clock pickup note○Print percent signs and aligned values○Line up a cleaning report○Evaluate expressions before printing○Divide reflectors among trays✦Module Quiz
○Comparisons and True or False○How if and else Choose a Path○Choose a Ticket Message○Select a Fixed Choice with switch○Choose a Service Desk✦Module Quiz
○For Loops: Repeat a Known Number of Times○Add Daily Contributions○While Loops: Repeat While a Condition Holds○Make a Countdown○Run Once with do while○Label a Two-Row Shelf○Label Tool Drawers✦Module Quiz
○Define and Call a Function○Follow a Function Call and Its Return Value○Return a Square○Declare Before a Function Call○Declare and Convert✦Module Quiz
○Arrays and Zero-Based Indexes○Add Array Elements○Count Array Slots Safely○Average Workshop Ratings○Rows and Columns in Memory○Total a Two-Row Grid✦Module Quiz
○C Strings and the Null Terminator○Count a Label○Compare Complete Strings○Verify a Pickup Code○Visit Each Character○Count a Letter in a Label✦Module Quiz
○Pointers: Addresses and Dereferencing○Update Through a Pointer○Pass an Address to a Function○Swap Two Counts○Array Addresses and Offsets○Total with an In-Bounds Pointer○Null, Validity, and Lifetime○Handle an Optional Pointer✦Module Quiz
○Pass an Array and Its Length○Total Readings in a Function○Change Array Elements Through a Parameter○Update Each Stock Count✦Module Quiz
○Define a Supply Record○Record Thread Supplies○Update a Record Member○Update the Paper Stock○Walk an Array of Records○Total the Flyer Stacks○Pass a Record to a Function○Print a Badge Record✦Module Quiz
○One Value in Shared Storage○Record One Ticket Value○A Tag Tells You What Is Stored○Read a Tagged Repair Ticket○Compare Union and Struct Storage○Choose the Right Storage✦Module Quiz
○Read Bits with AND○Check an Equipment Flag○Turn a Flag On with OR○Mark a Kit Ready○Toggle and Clear Individual Flags○Toggle a Warning Flag○Move a Bit into Position○Build a Position Mask✦Module Quiz
○Include the Right Header○Measure a Label with strlen○Guard a Macro Default○Set a Fallback Badge Limit○Include Code Only for Debug Builds○Show an Inventory Diagnostic When Enabled○Parenthesize a Simple Macro○Keep a Macro Calculation Grouped✦Module Quiz
○Name a Status with enum○Confirm an Application Status○Alias a Record Type with typedef○Initialize a Ribbon Record✦Module Quiz
●Where the storage comes from○Request and Release an Array○Store Three Repair Counts○Start Allocated Counters at Zero○Start Station Counters at Zero○Allocate and Release Records○Allocate the parts report✦Module Quiz
○Print a Formatted Label○Print the carving sign○Print Characters with putchar○Build a two-letter mark○Format into a Bounded Buffer○Prepare the shelf label○Write a Line to stdout with fputs○Post the ready notice○Input and Diagnostics in a Local Terminal✦Module Quiz
Allocated Memory and Lifetime

Where the storage comes from

Storage that outlives a function call

A function can calculate a number and return it. Returning access to an array takes more care: the caller needs storage that is still alive when it uses the elements. The type names from the previous section describe what an object holds; its storage duration tells us how long that object exists.

Three lifetimes you will use

Storage durationFamiliar exampleWhen its lifetime ends
AutomaticAn ordinary local int or fixed-size arrayWhen execution leaves its block, including by returning
StaticA global variable, a local declared static, or a string literalAt the end of the program
AllocatedStorage obtained with malloc or callocWhen you release it with free

These are the durations needed here, not an exhaustive list of C's storage categories. C also has thread storage duration, which this course does not use. A local static variable keeps its value between calls, even though its name is only usable inside its scope. A string literal such as "Ready" has static duration; that does not make its characters writable.

Reading a stack-and-heap picture

When main calls a helper, main waits while the helper runs. We often draw the active calls as stack frames: one frame for the caller and another for the callee. Ordinary local variables belong to the current call. Returning removes the callee's frame from this model.

Allocated storage is usually called the heap. We draw it outside those frames because returning from a function does not release it. Stack and heap are a conventional implementation model, not a memory layout required by C. There are no promised numeric addresses, growth directions, or gaps between these boxes. An optimizing compiler may keep locals in registers or inline a call; the lifetime rules still apply.

Read the rows as successive moments for one allocation: the left box is a pointer object, and the right box is the separately allocated integer.

A pointer is not the object it points to

In the picture, the helper's pointer p is an automatic object. The integer obtained from malloc is a different object, with allocated duration. p holds its address. Returning that address copies a pointer value to the caller; it does not move the allocated integer or extend the helper's local variables.

Follow this complete example now, then run the smaller allocation demo in the next lesson. <stdlib.h> declares malloc and free. NULL means that no usable object was obtained. The next lesson explains the byte count in the request.

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

/* On success, the caller owns the returned allocation. */
int *make_count(void) {
    int *p = malloc(sizeof *p);
    if (p == NULL) {
        return NULL;
    }
    *p = 6;
    return p;
}

int main(void) {
    int *count = make_count();
    if (count == NULL) {
        return 1;
    }
    printf("Count: %d\n", *count);
    free(count);
    count = NULL;
    return 0;
}

The successful path prints Count: 6. While the helper runs, p points to the new integer. After return p, the local variable p is gone, but the integer remains alive and count points to it. We call main the owner because it now has the responsibility to release that allocation. Ownership is an agreement in our program, not a check that C performs for us.

Contrast that with declaring int local = 6; inside the helper and returning &local. That would return the address of an automatic object whose lifetime ends as the helper returns. The caller must not use that address. Returning an ordinary value such as local is fine: the integer value is copied before the local object's lifetime ends.

After free(count), the allocated integer is gone too. Do not read it, write it, or free it again through any old pointer. Assigning NULL to count records that this variable no longer points to usable storage; it does not repair other copies of the old address. free(NULL) does nothing, but dereferencing NULL is invalid.

If the helper lost its only pointer without returning it or freeing it, the allocation would still exist with no way for the program to release it. That is a memory leak. Keep one clear owner and release each successful allocation exactly once, after its final use. Never pass the address of an automatic variable or a string literal to free.