Zuhaitz Profile picture
Sep 8 7 tweets 3 min read Read on X
We know about malloc() and free() but they can be pretty slow. What if I told you there's a faster technique used for high-performance C programming?

Let's talk about Memory Arenas.

(Thread)Image
What IS a memory arena?

A memory arena is a large, contiguous block of memory that you allocate once at the beginning of a task.

It's helpful because instead of using malloc() for each element, we can just work with our allocated memory.Image
First advantage: incredibly fast allocation

Allocating from a simple arena can be as fast as a single pointer addition. You just bump a pointer forward to reserve a new chunk of memory.

Here we have a conceptual code. This is orders of magnitude faster than malloc(), which has to search for free blocks and manage metadata.Image
Second advantage: instant deallocation

So, you don't free individual objects in an arena.

When you're done with all the objects, you free the entire arena at once.

In its simplest form, this can just be resetting a pointer:Image
The trade-off

So, if it's that good, what's the issue?

In a simple arena, you cannot free individual objects. You can only free the entire collection of objects at once.

This is why arenas are a specialized tool.
When to use arenas

Arenas are actually great for tasks where you allocate many objects that all have a similar, well-defined lifetime.

- Batch processing: Processing a single web request, compiling a single file, or rendering one frame of a game (for videogames, believe me, it's useful).

- Data structures: Building a complex data structure like a tree, where you know you'll destroy the entire tree at the same time.
Memory arenas are a class C pattern that trades the flexibility of freeing individual objects for massive gains in allocation and deallocation speed and cache performance.

If you found this useful, follow for more C / low level daily threads!

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Zuhaitz

Zuhaitz Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @zuhaitz_dev

Sep 6
Ever noticed that when you use compiler optimizations (-O2, -O3), your program gets faster but the file size gets bigger?

This is not a paradox.

(Thread) Image
The space-time trade-off

To make a program run faster, a compiler will often generate more machine code to save the CPU from doing work at runtime.

You are trading space (a larger binary) for time (faster execution).

Two common techniques that do this are function inlining and loop unrolling.
Function inlining

A function call has overhead (pushing to the stack, jumping).

The compiler can inline a function by copy-pasting its code directly where it's called.Image
Read 7 tweets
Sep 5
Function pointers: this time you will understand them

(Thread)Image
What IS a function pointer?

Just like normal pointers hold the memory address of a variable (like an int or a char), a function pointer holds the memory address of a function.

In C, when you compile your code, each function has its specific address in the executable memory.

A function pointer is simply a variable that points to that starting address.Image
The syntax

The syntax can look scary, but it's logical.

Let's break down a pointer that can point to any function that takes two ints and returns an int:

- int: The return type of the function.

- (*my_function_ptr): The name of our pointer variable. (The parentheses are a must, without them you'd be declaring a function that returns a pointer).

- (int, int): The types of the arguments the function takes.Image
Read 9 tweets
Sep 2
On June 4, 1996, the Ariane 5 rocket, carrying a payload worth half a billion dollars, exploded just 37 seconds after its maiden launch.

But what caused this? It wasn't a faulty engine or fuel leak. It was a single, uncaught software bug.

(Thread) Image
A decade of work

The Ariane 5 was the European Space Agency's new flagship rocket.

After a decade of development and an investment of over $7 billion, its first flight was meant to be a triumph.

Everything seemed perfect, liftoff was flawless. For 30 seconds everything was nominal.But then the rocket suddenly veered violently off course, and triggered its self-destruct system.

You can watch what happened over here: youtu.be/PK_yguLapgA?si…
The fatal flaw

The investigation revealed the root cause, a data conversion error.

A 64-bit floating-point number representing the rocket's horizontal velocity was being converted into a 16-bit signed integer.

The Ariane 5 was much faster than its predecessor, so that velocity became larger than 32,767 (The maximum value a 16-bit signed integer can hold).

The result was an integer overflow.Image
Image
Read 6 tweets
Sep 1
Today we will talk about something different.

We will talk about Red Star OS, a North Korean operating system. I will show you how to bypass some possible issues and show some reverse engineering! Image
The first thing we start with is the installation process. Surprisingly, it allows us to choose our location and timezone globally, which is already suspicious as it is a North Korean OS. Maybe it isn't completely. Image
After the installation, I was able to get to the terminal (it was pretty hidden, and my Korean isn't amazing), but the issue is that I couldn't write properly. I tried changing the text encoding, keyboard layout, ... but it was still giving issues.

So I decided to modify the ISO itself. It wasn't that hard, we only had to change the language to English (lang=en).

This will not change the language for everything, but it does change the language of the installation process and we can use the terminal now!Image
Image
Read 9 tweets
Aug 29
If you are learning C, you must have heard the word "compiler" endless of times. You know that it makes your code an actual program (a binary).

But how does it work? Let's explain it step by step with a simple hello world program!

(Thread) Image
Let's say that, when we use the compiler, we usually go directly from the source file to the binary.

You can do this with (we will use gcc):

gcc hello.c -o hello

But we can go step by step with some specific flags! Image
Preprocessing

The preprocessor handles all the lines starting with #. It strips comments and replaces #include with the actual content of the standard I/O header file.

We can achieve this with:

gcc -E hello.c -o hello.i

The resulting "hello.i" file is huge, but at the very end, you'll find our code, minus the comments:Image
Read 7 tweets
Aug 27
Want to learn C from scratch but don't know how?

Here I will provide you many of the concepts you will need!

(Thread) Image
Let's start with something simple: variables & types.

C is statically typed, which means that you have to specify (declare) what the variable is.

Think of it like your HS physics teacher forcing you to write the units.

We have some key types: int, float, double, char. int is for integers; float and double for rational numbers; char for characters. Really straight forward.

If you want to learn more about types: geeksforgeeks.org/c/data-types-i…

[NOTE]: remember, sizes depend on architecture (for example: 32-bit vs 64-bit).Image
You can also write notes inside the code. These notes are known as comments.

Whatever you write here will note be considered code, therefore you can write explanations or tasks (TODOs). Image
Read 20 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(