What is Memory Waste in String Arrays- Embedded C Training For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Memory Waste in String Arrays

Free C programming course: measure the padding hidden inside a two-dimensional char array, and learn why it matters for embedded C programming on small RAM.

Every row of a 2-D string table reserves the same number of bytes, whether the text needs two of them or twenty. In this lecture of our free C programming course you will count that memory waste in string arrays, write a short program that reports it, and see why firmware engineers care. A microcontroller with 16 KB of RAM cannot afford hundreds of silent padding bytes, and this free embedded C course wants you to spot them before the linker map does.

What You Will Learn

  • Why a fixed-width row leaves unused bytes
  • A simple formula for wasted bytes per string and per table
  • How to measure waste with sizeof and strlen
  • How to protect a table from a too-small row with _Static_assert
  • Where such a table lives on a microcontroller: RAM versus flash
  • How to choose LEN sensibly

Prerequisites

Finish the previous lecture on the array of strings in C first, because we reuse the same periph table. You also need strlen from <string.h> and the meaning of sizeof. Everything here is plain C17 and compiles with gcc -std=c17 -Wall -Wextra.

Why Memory Waste in String Arrays Happens

A two-dimensional array is a rectangle. The compiler multiplies the two subscripts and reserves that many bytes, and it cannot make one row shorter than another because row starting addresses must follow the simple rule start = i * LEN. If a string needs fewer than LEN bytes, the leftover bytes still belong to that row. Nothing else can use them, and your program does not normally read them either. That is padding.

The waste formula

For one string, the bytes it really needs are its length plus one for the NUL. For the whole table:

reserved = COUNT * LEN
used     = sum over all rows of (strlen(row) + 1)
wasted   = reserved - used
StringNeeds (with NUL)ReservedPadding
UART583
I2C484
SPI484
GPIO583
TIMER682
Total244016

Sixteen of forty bytes, which is 40 percent of the table, carry no information at all.

Used bytes versus padding per row (LEN = 8)
RowText bytesNULPadding bytes
periph[0] UART413
periph[1] I2C314
periph[2] SPI314
periph[3] GPIO413
periph[4] TIMER512

Measuring the Waste in Code

Instead of counting by hand, let the program do it. Save this as waste.c:

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

#define COUNT 5
#define LEN   8

int main(void)
{
    char periph[COUNT][LEN] = { "UART", "I2C", "SPI", "GPIO", "TIMER" };
    size_t used = 0;

    for (int i = 0; i < COUNT; i++) {
        size_t need = strlen(periph[i]) + 1;
        printf("%-6s needs %zu, reserved %zu, wasted %zu\n",
               periph[i], need, sizeof periph[i], sizeof periph[i] - need);
        used += need;
    }
    printf("total reserved = %zu\n", sizeof periph);
    printf("total used     = %zu\n", used);
    printf("total wasted   = %zu\n", sizeof periph - used);
    return 0;
}
gcc -std=c17 -Wall -Wextra -o waste waste.c
./waste

Expected output:

UART   needs 5, reserved 8, wasted 3
I2C    needs 4, reserved 8, wasted 4
SPI    needs 4, reserved 8, wasted 4
GPIO   needs 5, reserved 8, wasted 3
TIMER  needs 6, reserved 8, wasted 2
total reserved = 40
total used     = 24
total wasted   = 16

Notice that sizeof periph[i] gives the row width (8), not the string length. That difference between sizeof and strlen is one of the most common interview topics, and here it is visible in a single program.

Guarding LEN at compile time

The opposite problem is a row that is too small. A compile-time check catches it long before the firmware runs. _Static_assert is part of C11 and later:

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

#define COUNT 4
#define LEN   6

_Static_assert(sizeof("TIMER") <= LEN, "LEN too small for TIMER");

int main(void)
{
    char tag[COUNT][LEN] = { "ADC", "DAC", "TIMER", "PWM" };
    size_t used = 0;

    for (int i = 0; i < COUNT; i++)
        used += strlen(tag[i]) + 1;

    printf("reserved = %zu, used = %zu, wasted = %zu (%zu%%)\n",
           sizeof tag, used, sizeof tag - used,
           (sizeof tag - used) * 100 / sizeof tag);
    return 0;
}
reserved = 24, used = 18, wasted = 6 (25%)

The expression sizeof("TIMER") is 6 because a string literal includes its NUL. If you shrink LEN to 5, compilation stops with your message. Shrinking is exactly what you want a build to refuse.

Why Embedded C Programming Cares

On a desktop, forty bytes is nothing. On a microcontroller it adds up. Imagine a table of 64 log messages, each declared with LEN of 48 so that the single longest message fits. That table reserves 3072 bytes. If the average message is 18 characters, roughly 1900 of those bytes are padding. On a part with 20 KB of RAM that is nearly ten percent gone for nothing.

RAM or flash?

A non-const 2-D array that you initialize with literals is placed in the initialized data section. Its starting values are stored in flash, and the startup code copies the whole rectangle, padding included, into RAM before main runs. That costs both flash and RAM, and it costs boot time.

Where a non-const string table lives
Flash: initial image of table (40 bytes)startup copy loopRAM: working table (40 bytes)

If the table never changes, declare it const. A const char table can stay in flash only, and the copy into RAM disappears:

const char periph[COUNT][LEN] = { "UART", "I2C", "SPI", "GPIO", "TIMER" };

The padding still takes flash space, but RAM stays free. Exact placement depends on your toolchain and linker script, so confirm with the map file for your target.

Try it yourself

Change LEN in the guard example from 6 to 8 and run it again. Reserved bytes grow to 32 while used bytes stay at 18, so the waste rises to 14 bytes. Then change LEN to 5: the build stops with your assertion message, because TIMER needs six bytes. Watching the build fail on purpose is the quickest way to trust the check. Finally, add one very long entry such as a 20-character name and see how a single outlier forces every row to grow.

Choosing a Good LEN

ApproachEffect
LEN equals longest string plus oneSmallest safe rectangle for this table
LEN rounded up for future entriesSome extra padding, easier to extend
LEN guessed generously, such as 64Safe but wasteful; avoid on small MCUs
Wildly different string lengthsRectangle is a poor fit; prefer an array of pointers (coming up)
Common mistake: deciding LEN from the strings you have today. When a new, longer entry is added later, a literal that does not fit either fails to compile or, with a run-time copy, overflows into the next row. Pair the table with a _Static_assert and the problem becomes a build error.

Best Practices

  1. Report waste once during development with a helper like the one above, then decide whether the rectangle is acceptable.
  2. Mark read-only tables const so they can stay in flash.
  3. Keep the strings in a table similar in length; one very long outlier ruins the whole rectangle.
  4. Use _Static_assert to tie LEN to the longest literal.

Performance and security notes

Padding does not slow lookups, but it increases the amount copied at startup and the amount scanned if you ever use memcpy over a whole row. For security, remember that padding bytes are zero only when you initialize with literals. A row filled later by your own code may contain old data after the NUL. Never assume bytes after the terminator are zero unless you cleared them.

Summary and Key Takeaways

  • A 2-D string table reserves COUNT * LEN bytes regardless of string lengths.
  • Waste equals reserved bytes minus the sum of strlen + 1 of every row.
  • sizeof row is the width of the row, while strlen row is the text length.
  • Use _Static_assert to guarantee LEN fits the longest literal.
  • Tables that never change belong in const storage.

Conclusion

Understanding where bytes go is a core habit of embedded C programming. You measured the padding in a small table, saw how it scales on a constrained device, and learned two tools, const and _Static_assert, that keep a table honest. Next, we look at how to put new text into these rows, because direct assignment is not allowed.

Frequently Asked Questions

Why does a 2-D char array waste memory?

Every row has the same width, so shorter strings leave unused bytes at the end of their rows.

How do I calculate wasted bytes in an array of strings?

Multiply the row count by the row width, then subtract the sum of each string length plus one.

What is the difference between sizeof and strlen for a row?

sizeof gives the bytes reserved for the row; strlen counts characters before the NUL.

Does const really save RAM on a microcontroller?

Usually yes. A const table can stay in flash, avoiding the startup copy into RAM, though this depends on your linker script.

What does _Static_assert do?

It checks a condition at compile time and stops the build with your message if the condition is false.

Is the padding always zero?

Only when the row was initialized with a literal or cleared. Later writes can leave old bytes behind the NUL.

Keep Learning Embedded C for Free

This free C tutorial continues with safe ways to assign and copy strings into array rows.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →