r/C_Programming • • 14d ago

Question A question about arenas.

I worked in C for years . i have used arenas a lot in the past. Today i have to modify an old c program , nothing difficult but i found something that made me think. Who developed the code ( very well written and documented ) used an arena for allocating variable.

What 's seems to me strange is that he did not used an heap memory area ( malloc ) but it used a char [] buffer and used it for its arena . At that point he could obviously allocate directly variable in stack instead he grabs all its variable from that buffer . Why a choice like that ? i thought for the CPU cache L1/L2 and so on ( all the "arena" will likely be in cache of the cpu ) but it is only an ipotesys and i was asking to you , in your opinion , the reason of a such choice .
Just curiosity .

Thanks

PP

38 Upvotes

38 comments sorted by

5

u/ffd9k 14d ago

Storing lots of data on the stack is a very bad idea, because the stack is very limited (just a few megabytes by default).

Storing lots of data in a big buffer declared as a static/global variable is fine. It will typically be stored in the .bss section which can use much of the huge address space and all available RAM/swap, so on a modern computer you can store gigabytes like this without a problem.

2

u/Ok_Outlandishness906 14d ago

it was something like 64k of buffer , not that much

19

u/treemcgee42 14d ago

Was it a global array? If the objects are in a global array, they can be used non-locally, e.g. across different functions. This is nice for libraries to completely avoid heap allocation, in case the user has hard requirements or wants to manage all dynamic allocations themselves.

7

u/mjmvideos 14d ago

Oh!!! hypothesis!!

18

u/runningOverA 14d ago

Among other things, using char[large] instead of malloc() reduces one level of indirection at run time.

The compiler knows the address of the char[] buffer during compile time, but not the malloc()-ed space.

ie. char buffer is faster.

2

u/hemzerter2 14d ago

I am not sure to understand, how can the compiler not know the malloc space address ? Does it not refer simply to the pointer ? I don’t really know how compilers work maybe that’s why I don’t understand your message

1

u/AntMan5421 8d ago

how can the compiler not know the malloc space address ? Does it not refer simply to the pointer ?

malloc allocates memory in the heap address space, which might have data not only from your code, but also from other libraries. your libc keeps track of the chunks used in the heap segment and finds a space for your data, calling to the kernel to increase heap using brk and sbrk system calls. heap is on the oposite of the stack in virtual memory and grows upwards (but that might not be the case in physical memory!)

and btw malloc(size_t n) returns a pointer to the reserved chunk of size n bytes

0

u/beephod_zabblebrox 13d ago

what

its the same pointer, most addresses are runtime-dependent anyway

10

u/tstanisl 14d ago

On some embedded platforms the stack may be very limited (like a few kiBs). Even though RAM is a lot larger. Where the char[] buffer is allocated? Is it a global variable?

12

u/HarderFasterHarder 14d ago

Also, malloc is almost always forbidden for bare metal stuff I've worked on... I've used a custom "allocator" with an empty array of structures many many times. It's not always due to limited ram, but usually the rule is no dynamic memory, static only so that the usage is "deterministic". I put that in quotes because the call stack is not always easily determined and have had a few projects where this had bitten us in the butt.

This variable thing OP is talking about does sound weird though.

5

u/ReallyEvilRob 14d ago

No need for malloc if using a global or static array.

1

u/gremolata 14d ago

So that he could pass arena to other functions being called?

Or substitute it later for a version that's not stack-allocated?

0

u/Ok_Outlandishness906 14d ago

temporary variables are taken on the stack by function ,the 2 datastructure he used are taken from the buffer and some global stuff also.

2

u/UnrealHallucinator 14d ago

Stack allocated memory is faster and the array would be contiguous in memory, so better cache locality as well. Also like another comment said, the compiler knows where the buffer is.

2

u/LumpySpecial5351 14d ago

I always thought that it was the granularity, the overhead for each allocation that drove the use of arenas. I believe that an malloc of one byte costs more than one byte, whereas an arena can be tailored per application.

I strive ever towards fully static memory allocation on my embedded ESP32 projects and avoid malloc and have never used an arena.

Burtrum

1

u/tharold 14d ago

Yes, and apart from malloc having to allocate extra space for its own bookkeeping, space can also be lost due to unnecessary alignment. For example, no need to align if char buffers are requested.

2

u/August_72_West 14d ago

What is an arena?

3

u/tstanisl 14d ago

Basically, it is a pool from with a bunch of related objects is allocated. The arena owns all those objects thus all objects can be released at one time. This can simplify lifetime management in some applications. Moreover, arenas are typically implemented with linear allocators making them extremely fast.

-1

u/LemonLord7 14d ago

Short answer: a bunch of bytes on the stack you give out and use instead of using malloc.

3

u/ReallyEvilRob 14d ago

Not on the stack since the lifetime would be limited to the stack frame where the arena was allocated. An arena needs to be statically allocated.

2

u/LemonLord7 14d ago

That’s true, although couldn’t an arena be on the stack and injecting into some function at top level in main function?

1

u/R3D3-1 14d ago

Sure, but stacks have a tendency of having much tighter limits applied than other parts of memory.

1

u/tharold 14d ago

Not only that, C doesn't warn you if you run out of stack, unlike malloc which at least will return an error. It's up to the OS to handle stack overflows.

1

u/ReallyEvilRob 14d ago

Sure, but why do that? Making it global or static better shows your intent.

1

u/LemonLord7 14d ago

I shouldn’t have written stack in my first comment. But got thinking when you said an arena needs to be statically allocated. Could inject a char array to some lib or high level function for different sizes of array. Although even then it might be better to have the array be static.

1

u/glasket_ 14d ago

Arenas can be on the stack or heap. Stack-based arenas are useful when you would otherwise just reset the arena at the end of a function anyways; helps to prevent mistakes where the reset gets moved around or a branch gets introduced and nobody adds the reset for the new path.

1

u/ReallyEvilRob 13d ago

Sure, as long as you don't need those allocations after the function returns.

1

u/Scootztheprgrmmer 14d ago

Saving memory or saving time that seems to he the reasoning here but yea you'd think malloc would be used but if it could save a bit of time the other way may be better definitely a unique way to do it

1

u/DawnOnTheEdge 13d ago

One reason to use arenas is so different threads aren’t constantly blocked, waiting for their turn with the global heap.

Another is to avoid freeing each allocation individually. In many algorithms, a task needs some scratch space that can all be freed at once, but must be dynamically allocated of unknown size, or might need to be returned from helper functions, so local variable won’t suffice. Linux does provide an alloca() function to dynamically allocate bytes on the stack, and C99 introduced a now-deprecated variable-length array feature.

1

u/Dangerous_Region1682 13d ago

Since most processors these days cache virtual addresses as well as physical addresses assuming things are going to be retained in the L1 cache as long as you think is unlikely as context switching will likely displace more than you would desire.

The virtual address defines the cache slot if you like and the physical address defines the process effectively. Yes I know it’s more complex than this as there’s a TLB at play here.

The reality is you might expect an arena to be largely cache by access activity, but the reality is once you get more than a few context switches away the L1 cache is largely flushed of your data.

Yes I known this isn’t a 100% accurate view of how things exactly work, but the reality is that an L1 cache is rarely as useful as you would think on systems with context switches and many switches to kernel space and back. The same cache is used by the things you don’t see when looking at one process actually running on a time sharing system with interrupt handling, system call occurrences and context switches going on. They are great things to have for performance improvement within your time slice but entry persistence is not as good as one would think.

1

u/PlacentaOnOnionGravy 13d ago

Sounds like deterministic memory management

1

u/FLMKane 10d ago

The answer to all C programming arenas is Quake 3 Arena.

/s

1

u/AntMan5421 8d ago

I like to do this too if i know I won't exceed the stack size! i think stack size >> L1 cache so in the end it's more about how you lay out your variables in the buffer than anything else. but I might be in the wrong here :)

0

u/rubidus-api 14d ago

An arena inside a char array, whether it's on the stack or static, has a serious problem in principle. Under C's effective-type rules, an object with a declared type always has that type, so a declared char array stays char, and accessing parts of it as a struct isn't allowed. Copying the data in with memcpy doesn't fix it either: memcpy passes the effective type on only to memory that has no declared type, such as memory from malloc. The aliasing rule lets you access any object as char, not a char array as anything else. In practice this almost never causes trouble, and code like this is everywhere, but I think a C programmer should at least know about this contradiction. (If it worries you, put the arena in memory from malloc, or build with -fno-strict-aliasing.)

While you're at it, make sure the buffer is aligned for what you put in it (for example alignas(max_align_t) in C11); C doesn't promise that for a char array.

Apart from that, and from where it lives, an arena on the stack isn't very different from one on the heap. Allocating on the stack is usually faster than a heap allocation, but when you take one large block once, that hardly matters. The cache doesn't care whether memory is on the stack or the heap either; what counts is what you touched recently. Unless other hot variables sit right next to it, I don't think a stack arena is better or worse for cache hits than a heap one. And a 64 KB buffer is already larger than the L1 data cache of most x86 cores (32–48 KB), so the whole arena can't stay in L1 anyway.

Where malloc isn't allowed, you can build the arena in a static char array. You get the same benefits as with a heap arena: you take the memory all at once when you choose, and release it (or reuse it for something else) when you choose.

So what's the difference from just using local variables? I still think it's the same thing: you decide when a group of objects comes into being and when its space is released or reused, even across functions. Local variables live exactly as long as the block they're declared in, so you can't control their lifetimes that freely.

Arenas also combine well with pools. Say you create and destroy structs of one type very often. You can keep an array of pointers to that type as a stack: when an object is no longer needed, push its address, and the next allocation pops it and reuses the space. That's what's usually called a pool with a free list.

And since the code only talks to an arena, the same code can run on top of a static buffer, a stack buffer or malloc. If it's shared with environments where malloc is available, that alone is a good reason to write it this way.

It isn't completely free, though. Objects carved out of an arena usually have to live in memory, so the compiler can't keep them in registers the way it often does with locals, and tools like AddressSanitizer can't see the boundaries between objects inside one buffer.

Finally, this is more about having an allocator layer than about arenas as such, but once all allocation and release go through one place, you can add debugging or monitoring there in one go.

1

u/Different_Panda_000 4d ago

I'm working with an application that has a network communication layer using UDP that allocates static unsigned char buffers and then partitions the buffers into different components with a different type throughout the code. Basically it's just a large union that indicates with a fixed preface struct what follows indicating which of the various message and response structs are laid on top of the memory area to process the data.

Compiles fine, no warnings, works fine. The compiler figures out offsets and everything.

1

u/rubidus-api 4d ago

Yes — in practice, treating a char (or unsigned char) array like memory from malloc() rarely causes trouble, aside from the chance that the array's start address — or an offset inside it — doesn't meet the alignment requirements of the types laid on top. (If the buffer is actually declared as a union rather than accessed by casting pointers into a raw unsigned char[], C handles the alignment and union member access directly.) Using a byte array this way is widely done, embedded systems often leave little choice, and I don't know of any real-world breakage caused purely by this pattern.

The catch is that compiling cleanly with no warnings and working today doesn't mean the standard guarantees it: effective-type violations don't require a diagnostic, and computing member offsets within each struct is separate from aliasing. Under C's strict aliasing rules as written through C23, there's no guarantee that it will always stay that way, or that a compiler won't transform it in an unexpected way when an optimization pass sees an opportunity. That's really all I meant: a programmer should at least know that this potential contradiction exists.

Out of curiosity, I looked into whether pointer provenance (as in ISO/IEC TS 6010) would solve this, and it turns out it isn't a provenance issue: provenance tracks which storage instance a pointer comes from and its bounds (so buf + offset inside a char array is already fine), while effective-type rules are a separate layer. Instead, there is a separate WG14 proposal adopted into the C2y working draft, N3254 ("Accessing byte arrays"). It gives properly aligned and sized, non-atomic character arrays the same effective-type treatment as memory with no declared type (like malloc()), bringing the standard closer to how real-world C code like yours is already written.

1

u/Different_Panda_000 3d ago

First of all thank you for bringing this up. I've been doing some reading and frankly I feel a bit less comfortable about this than I did previously.

Most of the data structures being used in my application are byte aligned or packed on a byte alignment using a pragma to inform Microsoft Visual Studio. This works fine on Intel and AMD as the compiler knows that there is a high probability of struct pointers containing an address that is not on a standard struct memory boundary.

For some machine instructions Intel requires alignment on a particular memory boundary. Some of the vector instructions have this requirement, I believe. The compiler may be using them but I've not written any explicit code to do so. I assume the compiler know what it is doing.

My understanding is that Effective Type has to do with the last data written to a particular memory location. When the data is written then it must be read back from that location using the same type as it was written and not doing so is Undefined Behavior.

So if my understanding is reasonably correct, by using a struct as a template to write data into a buffer, send it, receive it on the other side and putting the same sequence of bytes into the receiving buffer as was received then using the same struct to place an order on the bytes so that they become shorts and longs and chars then I'm obeying the rules.

Actually one of the things I worry about is that the code uses shorts and longs and ints and I'm wondering what is going to break should I recompile this source as x64 rather than x32.

I've just spent a few weeks cleaning up the network layer which had some funky pointer juggling and in general was really hard to read. At least now everything uses the proper structs and unions and comments are in place to provide some idea as to what is going on.

And I just fed this note into Gemini AI who told me I had a good understanding of Effective Types and was quite positive about what I'm posting before it then laid the Big Boom Hammer on me and told me the only reason I was getting away with this was because Microsoft Visual Studio isn't as good as GCC/CLang at optimizing.

Even Gemini AI is a Microsoft hater.

Here's what Gemini AI said about the network layer mechanics. As for the x32 to x64, the news looks troublesome. And I just saw that Microsoft is ripping out the WOW64 layer on their sever products so x32 applications won't run there unless WOW64 is manually installed. Windows 11 is probably next; getting rid of WOW64 eliminates legacy functionality and reduces the attack surface.

Your mental model of Effective Type—that memory takes on the type of the last value written to it, and must be read back as that type—is completely accurate under the C standard.

However, casting a raw network char buffer directly to a struct* on the receiving end is technically Undefined Behavior (UB) in standard C, even if the bytes match:

The memcpy rule: When you receive bytes over a socket into a char[] buffer (recv(sock, buf, ...)), the memory has no effective type yet (or its effective type is char). If you cast (struct MyPacket*)buf and read pkt->id, the C standard considers that a strict-aliasing violation because you never wrote a struct MyPacket into that memory—you wrote raw characters.

Why it works in MSVC: MSVC does not optimize based on strict aliasing rules (unlike GCC and Clang at -O2 or -O3, which will happily break pointer-cast network parsers).

The Standard-Compliant Way: To strictly obey Effective Type rules, allocate or declare the struct on the receiving side and memcpy the received bytes into the struct:

2

u/rubidus-api 3d ago

First, I wouldn't panic — turning messy pointer juggling into clear structs and comments is real progress, and you don't need to throw away weeks of work. A few separate topics got mixed together in what you read (and in Gemini's reply), so it may help to untangle them in order from the ground up — apologies if some of the earlier points are already familiar.

1. Alignment: Every type has an alignment requirement, meaning its address normally has to be a multiple of N. Some architectures (like x86/x64) tolerate unaligned scalar accesses, and extensions such as #pragma pack(1) allow 1-byte alignment at some performance cost. One caveat for your note on vector instructions: the compiler only tracks that unaligned possibility while accesses go through the packed struct type itself — if you take a plain int * or long * to a packed member or cast an unaligned pointer to an unpacked struct, the compiler can assume normal alignment and emit aligned-only instructions.

2. Struct padding: Because of alignment rules, the compiler inserts padding between struct members (and possibly at the end), while C guarantees that members stay in their declared order.

3. Wire format, fixed-width types, and serialization: Different platforms, compilers, or OSes can disagree on alignment, padding, integer widths, and byte order, so network protocols need a shared wire layout — usually handled through serialization. For anything going over the wire, prefer fixed-width types from <stdint.h> (int16_t, uint16_t, uint32_t, etc.) over short, int, or long so sizes don't drift across targets. As long as both sides agree on the byte order and field layout and decode it consistently, you can follow one side's layout or use a packed layout with no padding like #pragma pack(1) — keeping in mind that #pragma pack(1) addresses alignment and padding only, not the aliasing rules below.

4. malloc()**:** When malloc() is called, it does not yet know what type of object you will place in the block, so its returned pointer must satisfy the alignment of any fundamentally aligned type that can fit in the requested size. C23 (7.24.3p1, via N2293) states this explicitly as any object with a fundamental alignment requirement and size less than or equal to the size requested — so malloc(3), for example, does not need max_align_t alignment, though it still needs at least 2-byte alignment because a 2-byte type like int16_t fits in 3 bytes. Types stricter than alignof(max_align_t) need aligned_alloc().

5. memcpy() and untyped memory: Storage returned by malloc() has no declared type, so it starts with no effective type. C defines specific ways to give it one, including writing through a non-character lvalue or copying an existing object into it with memcpy(), which carries the source object's effective type over.

6. char arrays: A declared char (or unsigned char) array does not behave the same way under C through C23, because it already has a declared type, so its effective type stays that character array type. That is why overlaying structs onto a char[] buffer is common in real code yet technically contradicts the standard as written — the gap C2y's N3254 (linked above) is meant to close.

7. Effective type and strict aliasing: Effective type and strict aliasing exist so the compiler can tell whether two accesses can refer to the same or overlapping memory. Knowing that unrelated types cannot alias lets the compiler reorder loads and stores, keep values in registers, or eliminate redundant reads. In C's model, memory is therefore not just a raw address: what type it was declared or written as, and what type it is read through, both matter.

8. Applying this to your UDP receive buffer: This is why "the sender filled it from a struct and the receiver reads the same struct" still trips the rule — and it is also the gap in Gemini's summary. The "memory takes on the last type written" rule only applies to untyped (malloc()) storage, not to a declared unsigned char[], and effective type only exists inside one C program's execution, never on the wire. On the receiving side, the compiler only sees recv() writing raw bytes into a declared unsigned char[], never a struct write. (One important check on your recent cleanup: if the buffer itself is actually declared as a union containing both the unsigned char[] and your message structs — rather than casting a union * or struct * onto a standalone unsigned char[] — then C already allows accessing the union members directly, aside from alignment, padding, and wire-format rules.) Otherwise, declaring a struct on the receiving side and memcpy()ing into it already avoids both effective-type and unaligned-access UB. Also, MSVC skipping strict-aliasing optimizations is a deliberate compatibility choice for legacy Win32 codebases rather than weak optimization, and GCC/Clang rarely break an opaque recv() followed by a single struct read in isolation — trouble mostly shows up when conflicting typed accesses meet in the same optimization scope.

9. Writing fast, safe packet code in practice: Many people avoid memcpy() because it looks like an expensive function call, so they cast unsigned char * to struct * instead. In reality, when the size is a small constant (2, 4, or 8 bytes), an optimizing compiler treats memcpy() as a built-in, removes the function call completely, and turns it into a single ordinary CPU load or store instruction. Going one step beyond memcpy() into a packed struct, you can keep your in-memory structs completely normal (no #pragma pack(1) needed) and read and write fields directly with tiny static inline helpers:

    static inline uint16_t read_u16(const unsigned char *p) {
        uint16_t v;
        memcpy(&v, p, sizeof v);
        return v;
    }

    static inline uint32_t read_u32(const unsigned char *p) {
        uint32_t v;
        memcpy(&v, p, sizeof v);
        return v;
    }

    static inline void write_u16(unsigned char *p, uint16_t v) {
        memcpy(p, &v, sizeof v);
    }

    static inline void write_u32(unsigned char *p, uint32_t v) {
        memcpy(p, &v, sizeof v);
    }

    /* On receive (after checking received_len >= 7): decode into a normal, aligned struct */
    struct Header hdr = {
        .type  = buf[0],
        .flags = read_u16(buf + 1),
        .seq   = read_u32(buf + 3),
    };

    /* On send (into a buffer of at least 7 bytes): encode fields directly */
    out[0] = hdr.type;
    write_u16(out + 1, hdr.flags);
    write_u32(out + 3, hdr.seq);

Writing it this way solves several problems at once: wire offsets (buf + 0, buf + 1, buf + 3) are explicit so compiler struct padding can never surprise you, <stdint.h> types keep field sizes identical across 32-bit and 64-bit builds, and there is no strict-aliasing or unaligned-pointer UB on either side. If your protocol uses big-endian (network byte order), you add one byte-swap inside read_u16/read_u32 and write_u16/write_u32. When I benchmarked a 7-field packet on x86-64 (GCC 14 and Clang 19 at -O2), #pragma pack(1) pointer casting and these small memcpy() helpers compiled to the exact same machine instructions with zero memcpy() calls left in the binary, taking ~2–3 ns per packet even when the packet started at an unaligned (+1) offset. (It is still worth checking MSVC's output directly, though modern compilers handle small fixed-size memcpy() similarly.)

Just as importantly, keep the scale in mind: 2–3 nanoseconds is only a handful of CPU cycles, whereas a single UDP socket call (recvfrom/sendto) takes hundreds to thousands of nanoseconds (and network travel takes microseconds or more). So safe decoding is effectively free. The things that actually make UDP networking fast are reusing pre-allocated receive/send buffers (like a static buffer, ring buffer, or pool instead of calling malloc()/free() per packet), keeping OS socket-call overhead down (such as sizing socket buffers so bursts don't drop packets, and batching I/O where supported), and keeping datagrams under the network MTU (commonly ~1,200–1,400 bytes) so packets don't get fragmented.

10. Moving from 32-bit Windows to x64: On your short/int/long concern, Windows x64 uses the LLP64 data model, so short (16-bit), int (32-bit), and long (32-bit) keep the exact same sizes as on 32-bit Windows. What does grow from 4 to 8 bytes is pointers, size_t, and pointer-sized Windows types (so wire structs containing pointers, or old Win32 code storing pointers/handles in a long or DWORD, will break), and if the peer is Linux or macOS 64-bit (LP64), long is 64-bit there — which is another reason moving wire structs to <stdint.h> fixed-width types pays off immediately.