topskill.dev
CoursesTracks
All courses/C Programming for BeginnersRequest and Release an Array
Allocated Memory and Lifetime
2 / 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

Request and Release an Array

Make room for a variable-sized count

The desk needs three counts in this example. We keep that count in a variable so the allocation expression can use it. malloc requests enough bytes for them and returns a pointer, or NULL on failure. The expression sizeof *counts measures one element without repeating its type. Because the allocated elements start without usable values, check the pointer first and initialize every element before reading it. Release the allocation with free after the last use.

Each row shows the same pointer and three-element allocation at a later moment; question marks mean uninitialized elements, not zeroes.

Read int *counts = malloc(n * sizeof *counts); in pieces:

  • counts is a pointer to int, not an array that remembers its length.
  • n is the number of elements. size_t is the unsigned integer type used for sizes and counts; keep n so loops know where to stop. Changing n after allocation would not resize the storage.
  • sizeof *counts gives the size of one int in bytes. Here sizeof uses the type without reading through the pointer. sizeof counts would measure the pointer itself, not the requested array.
  • Multiplying the element count by the element size gives the byte count that malloc expects. Do not assume every machine uses the same sizes.

fprintf(stderr, ...) sends the allocation-failure message to the diagnostic stream rather than ordinary output. The following section explains these streams in more detail.

In C, malloc's result converts to the destination pointer type without a cast. Include <stdlib.h> so the compiler knows the function's declaration. Our small, positive count is fixed; a general program must also reject counts whose multiplication would overflow or request an impractical amount of memory. Zero-size allocations are not needed here.

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

int main(void) {
    size_t n = 3;
    int *counts = malloc(n * sizeof *counts);
    if (counts == NULL) {
        fprintf(stderr, "Allocation failed\n");
        return 1;
    }
    for (size_t i = 0; i < n; i++) {
        counts[i] = (int) (i + 1);
    }
    printf("Total: %d\n", counts[0] + counts[1] + counts[2]);
    free(counts);
    counts = NULL;
    return 0;
}

The loop writes indexes 0, 1, and 2 with values 1, 2, and 3. Only then does printf read them and print Total: 6. Index 3 is outside this three-element array. No array element is read before it has a value. counts = NULL records that this variable no longer refers to usable storage. Dereferencing it would still be invalid, and the assignment cannot repair other copies of the freed address. For the exercise, repeat that order with different counts: allocate, check, fill, read, free.