topskill.dev
CoursesTracks
All courses/C Programming for BeginnersFormat into a Bounded Buffer
Input and Output Safely
5 / 10
← 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

Format into a Bounded Buffer

Build a label without overrunning its array

The supply desk builds a crate label in a fixed-size array before printing it. snprintf takes the buffer capacity, including room for the terminating null character. It returns the number of characters the full result would need, excluding the terminating null character, or a negative value on error. A return value at least as large as the capacity means truncation.

\0 is the null character that ends a C string; it is different from NULL, the null pointer used in allocation checks.

snprintf writes into the array, not to stdout. puts later prints the stored string and adds a newline. Supplying a capacity only helps if it is the real capacity: here label is an actual array, so sizeof label is its byte size. Inside a function receiving a char *, sizeof that pointer would not tell you the buffer capacity; pass the capacity separately.

c
#include <stdio.h>
int main(void) {
    char label[32];
    int written = snprintf(label, sizeof label, "%s #%d", "Crate", 7);
    if (written < 0 || (size_t)written >= sizeof label) {
        return 1;
    }
    puts(label);
    return 0;
}

Run it to see Crate #7. That text uses eight characters, so a complete stored string needs nine slots including \0. written is 8, not 9, and not the capacity 32.

The || condition checks for a negative result first. If that check succeeds, C does not evaluate the right side. Otherwise the cast to size_t lets us compare the nonnegative length with the array's capacity. An equal result also means failure to fit: the full text would leave no room for its terminator, so the stored text must be shortened.

This second, separate example deliberately uses an eight-byte array. It prints a status message instead of treating the shortened text as a complete label:

c
#include <stdio.h>

int main(void) {
    char label[8];
    int written = snprintf(label, sizeof label, "%s #%d", "Crate", 7);
    if (written < 0) {
        return 1;
    }
    if ((size_t)written >= sizeof label) {
        puts("Label did not fit");
        return 0;
    }
    puts(label);
    return 0;
}

Here written is still 8: it describes the full result, not how much was stored. The array contains Crate # followed by \0, so the program reports Label did not fit rather than printing an incomplete label.

With a positive capacity and a successful formatting operation, snprintf writes at most capacity minus one characters and terminates what it stores. It prevents writing past this correctly sized buffer, but it cannot decide whether a shortened label is acceptable. Our program rejects truncation. Do not substitute sprintf, which has no capacity argument.