Skip to content
systemcoding.dev
Debugging

Initialise Structs, Arrays and Heap Buffers Safely in C

Initialize C structs, arrays and malloc buffers so Valgrind reports no uninitialised reads, including the padding bytes that surprise you when data is written.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the C, C++ and GNU logos.

In C, a local variable or a malloc block holds whatever bytes were there before. Reading it is undefined behavior, and the program often appears to work because the old bytes happen to be zero on your machine. The bug surfaces on another compiler, another libc or another day, as a random branch or a leaked stack value in a network packet. Valgrind's Memcheck finds the read, as the post on --track-origins shows. This post covers the other half: how to initialize each kind of object in C so the report never appears. It uses GCC 14 and the C17 standard on Linux 6.12, with Valgrind 3.24 for the outputs, and it covers the one trap that catches careful people: padding bytes.

Locals: initialize at the declaration

An automatic variable with no initializer is indeterminate. The fix is to give every local a value where it is declared:

c
int count = 0;
double ratio = 0.0;
char *name = NULL;

If you cannot choose a meaningful value at the declaration, declare the variable at the point of first use, which C99 allows anywhere in a block. A variable that is assigned in both branches of an if is safe; one that is assigned in only one branch is the classic uninitialized read:

c
int level;
if (verbose)
    level = 2;
printf("%d\n", level);

Memcheck reports the printf argument as a use of an uninitialised value when verbose is false. GCC may warn about it with -Wmaybe-uninitialized at -O2, so build with -Wall -Wextra -O2 in CI as well as -O0 for debugging, because the warning depends on optimization.

Structs: use an initializer, then name the fields

For a struct, the shortest safe form is the empty initializer. In C17 and earlier, write {0}, which zero-initializes the first member and, by the rules of aggregate initialization, every other member:

c
struct config {
    int  verbose;
    int  retries;
    long timeout_ms;
};

struct config cfg = {0};

C23 allows {} for the same purpose, and GCC 13 and later accept it with -std=c2x and as an extension otherwise. Designated initializers set named fields and zero the rest, which also survives someone adding a field later:

c
struct config cfg = {
    .retries    = 3,
    .timeout_ms = 500,
};

Fields not named, here verbose, are initialized as if they had static storage duration, so integers become zero and pointers become null. This is the best way to build a struct in C, because adding a new member to struct config cannot leave it uninitialized in any place that uses this form. The failure mode is the opposite pattern, assigning each field by hand after declaring struct config cfg;, which silently skips whatever you add next.

Arrays

An array initializer works the same way. A partial initializer zeroes the rest:

c
int table[16] = {0};
char buffer[256] = "";

The second form initializes the whole 256-byte array, with the first byte zero and the remaining bytes zero too. Do not confuse it with char buffer[256]; followed by buffer[0] = 0;, which sets only the first byte. Code that later prints or copies sizeof buffer bytes reads the 255 undefined ones, and Memcheck reports an invalid use when the bytes go into a system call such as write.

For large arrays on the stack, an initializer costs time on every call because the compiler emits a clear. If the array is a scratch buffer that you fill completely before reading, skip the initializer and make sure the code fills every byte you read. Valgrind is the check that this is true.

Heap buffers: calloc or memset

malloc returns memory with undefined contents, and Memcheck tracks that. There are three safe patterns.

c
struct config *a = calloc(1, sizeof *a);

struct config *b = malloc(sizeof *b);
if (b != NULL)
    memset(b, 0, sizeof *b);

struct config *c = malloc(sizeof *c);
if (c != NULL)
    *c = (struct config){ .retries = 3 };

calloc multiplies its two arguments with an overflow check and zeroes the block, which also makes it safer than malloc(n * size) for arrays. The memset form is the one to use after realloc when you grow a buffer, since realloc leaves the new bytes undefined. The compound literal form sets the fields you name and zeroes the others, the same as a designated initializer, for heap objects. Use calloc by default for structures and arrays, and malloc only for buffers that the next statement fully overwrites, such as the target of read or memcpy with a known length.

After a growing realloc, clear only the new part:

c
size_t old_n = count;
size_t new_n = count * 2;
int *tmp = realloc(items, new_n * sizeof *items);
if (tmp == NULL)
    return -1;
memset(tmp + old_n, 0, (new_n - old_n) * sizeof *tmp);
items = tmp;

Forgetting this memset is one of the most common sources of the uninitialised-value reports that appear intermittently, because realloc sometimes extends in place and returns zeroed pages, and sometimes returns a recycled block.

Padding bytes: the trap

A struct often contains padding, unused bytes the compiler inserts to align fields. For this struct on x86-64:

c
struct record {
    char tag;
    int  length;
};

tag is at offset 0, length at offset 4, and bytes 1 to 3 are padding. The C standard says padding bytes have unspecified values after an initialization by = {0} or by member assignment. In practice, GCC often zeroes them when you use = {0}, but it does not guarantee it, and assigning members one at a time never touches them. That matters when the whole struct leaves the program as bytes:

c
struct record r;
r.tag = 'A';
r.length = 4;
write(fd, &r, sizeof r);

Valgrind reports the system call:

Text
==8120== Syscall param write(buf) points to uninitialised byte(s)
==8120==    at 0x497C1E4: write (write.c:26)
==8120==    by 0x109201: main (record.c:12)
==8120==  Address 0x1ffefffd54 is on thread 1's stack
==8120==  in frame #1, at pc 0x1091d9

Three of the eight bytes are padding, never written. Besides the Valgrind noise, the practical risk is information disclosure: the padding can hold bytes left over from earlier stack use, which then go to a file or a socket. Two fixes work:

  1. Zero the whole object first with memset(&r, 0, sizeof r) and then set the fields. This clears padding explicitly.

  2. Avoid writing structs as raw bytes. Serialize field by field in a defined byte order. This also removes dependence on the compiler's layout and on endianness, so the file or packet format becomes portable.

The second one is the right answer for any data that crosses a process or machine boundary. Raw struct writes are acceptable inside one program, for a cache file read by the same build.

Let the compiler help

GCC 12 and later, and Clang, provide -ftrivial-auto-var-init=zero, which zero-fills automatic variables that have no initializer. It is documented in the GCC option summary and is used in hardened distribution builds. It removes the stack-leak risk without touching the source, but it hides the bugs from Memcheck, because the memory is no longer undefined. Use it in release builds for defense in depth, and leave it off in the build you test with Valgrind. A related option, -ftrivial-auto-var-init=pattern, fills with a recognizable value, which makes an uninitialized read produce an obvious wrong answer in a test rather than a silent zero.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.