flak rss random

memory leak proof every C program

Memory leaks have plagued C programs for as long as the language has existed. Many solutions have been proposed, even going so far as to suggest we should rewrite C programs in other languages. But there’s a better way.

Presented here is a simple solution that will eliminate the memory leaks from every C program. Link this into your program, and memory leaks are a thing of the past.

leakproof.c
#include <dlfcn.h>
#include <stdio.h>

struct leaksaver {
        struct leaksaver *next;
        void *pointer;
} *bigbucket;

void *
malloc(size_t len)
{
        static void *(*nextmalloc)(size_t);
        nextmalloc = dlsym(RTLD_NEXT, "malloc");
        void *ptr = nextmalloc(len);
        if (ptr) {
                struct leaksaver *saver = nextmalloc(sizeof(*saver));
                saver->pointer = ptr;
                saver->next = bigbucket;
                bigbucket = saver;
        }
        return ptr;
}


Every allocated pointer is saved in the big bucket, where it remains accessible. Even if no other references to the pointer exist in the program, the pointer has not leaked.

It is now entirely optional to call free. If you don’t call free, memory usage will increase over time, but technically, it’s not a leak. As an optimization, you may choose to call free to reduce memory, but again, strictly optional.

Problem sovled!

Posted 19 Jan 2024 16:55 by tedu Updated: 19 Jan 2024 16:55
Tagged: c programming rants

how quick is the go compiler

Can you use go run for scripting? I wrote a small program to find out.

gorun.go
package main

import (
    "fmt"
    "os"
    "os/exec"
    "time"
)

func main() {
    start := time.Now()
    gogo := fmt.Sprintf(`package main
    import "fmt"
    func main() {
        fmt.Printf("the time was %s\n")
    }`, start)
    os.WriteFile("gogo.go", []byte(gogo), 0666)
    cmd := exec.Command("go", "run", "gogo.go")
    cmd.Stdout = os.Stdout
    cmd.Run()
    end := time.Now()
    fmt.Printf("that took %s\n", end.Sub(start))
}

$ go run gorun.go
the time was 2024-01-05 12:04:01.042488 -0500 EST m=+0.000077959
that took 329.81325ms

On my somewhat older m3 running openbsd, it takes about 330ms. On a less old chromebook, it takes about 100ms. Not bad. On an M1 macbook, it varies wildly between 150ms and 300ms.

So I think not fast enough for interactive use. Probably fast enough for a continuously changing cronjob, though I wonder why you wouldn’t change the inputs. But I guess if you’re a big believer in configuration through compilation, and also have constantly changing requirements, it’s fast enough to get by.

For comparison, yaegi is still 10x or more quicker at putting something on the screen.

go build

I almost exclusively run go build. Actually, I run make and that runs go build, because that’s how my fingers work. So it wasn’t until recently that I noticed that go run is as fast as it is. I was used to a very observable one second per build.

Turns out go build will run hg stat for every build, which go run skips, and that was the slowest part of the process. Easily remedied by switching to chg.

Posted 05 Jan 2024 17:23 by tedu Updated: 05 Jan 2024 17:23
Tagged: go

terminal smooth scrolling

I didn’t realize I needed this until I implemented it, and now, oh wow, can’t imagine life without it.

more...

Posted 28 Dec 2023 14:21 by tedu Updated: 28 Dec 2023 14:21
Tagged: software

from worst terminal to merely mediocre

Another month of poking around trying to make an almost useful terminal emulator.

more...

Posted 09 Dec 2023 18:30 by tedu Updated: 05 Jan 2024 20:14
Tagged: project software

vertigo

I wrote my own terminal and you won’t believe what happened next. I called it vertigo.

more...

Posted 15 Nov 2023 07:50 by tedu Updated: 15 Nov 2023 07:50
Tagged: project software

experiment with texture healing (monospace kerning)

The monaspace fonts introduced the idea of texture healing. I think of it as a sort of kerning for monospace fonts, though there’s probably some reason that’s technically incorrect. The basic idea is that some letters want more space, while others want less space, but this is hard to achieve in a monospace grid. And so they made a special font that includes alternative glyphs for letter pairs, so that i can donate some space to m.

more...

Posted 11 Nov 2023 22:02 by tedu Updated: 11 Nov 2023 22:02
Tagged: software

write your own terminal

What’s next after you write your own text editor and mail client? How about a terminal? In fact, as a practice exercise or to learn some new skills, I’d say a terminal emulator makes for a much better target. It’s composed of many parts, but at an approachable level, making it easy to make tangible progress. In this way, I think it makes for a good introductory project. At the same time, there’s a very long tail of features that can be added to keep things interesting.

more...

Posted 10 Nov 2023 07:44 by tedu Updated: 11 Nov 2023 18:42
Tagged: programming software

pasted bracket escapes escape bracketed paste

There’s a feature called bracketed paste supported by some “modern” terminals and editors, etc. When text is pasted from the clipboard, the terminal brackets it in special markers so that the receiving program knows it came from the clipboard and not the keyboard, and thus might turn off autoindent, etc.

It’s also supported by some shells, and I’ve lost count of how many times I’ve seen people claim that this is a security measure. Yeah, sure, it’s totally safe to paste commands from a website into the shell, because bracketed paste will let you review them before executing.

Does it work? The brackets delimiting the pasted text are just bytes as well, in band. A website can put the end paste sequence into the clipboard as easily as any other text.

Here are two buttons for testing. One runs ls. The second tries a little harder.

In testing, xterm turns the escape into a space, and nothing happens but a little gibberish spray. Other terminals appear to be not so lucky.

Posted 07 Nov 2023 19:47 by tedu Updated: 07 Nov 2023 19:47
Tagged: software web

fixing the other go loop bug

Go 1.21 added experimental support for fixing the loop capture bug. For reasons it’s never really bothered me, but the other loop bug does bite me some times. This is the one where the loop values are values.

I want references but go doesn’t have references.

values

The problem is easy to see when you’re looking for it, and hard to see when you’re glossing over the code.

func resetScores(players []Player) {
    for _, player := range players {
        player.score = 0
    }
}

Before and after “the” loop fix, this will dutifully set the player’s score to zero. But which player? An anonymous player that only exists in the loop. The array will remain unchanged. Ugh.

hand fix

Fixing this requires slightly rewriting the loop.

func resetScores(players []Player) {
    for i := range players {
        players[i].score = 0
    }
}

This looks kinda weird I think, and it’s not my first instinct to write it this way. I really just want a way to say hi, I’m iterating over the elements of this array, give me a reference to them.

mechanical fix

So let’s add references to go.

func resetScores(players []Player) {
    for _, &player := range players {
        player.score = 0
    }
}

This can be translated by powerful state of the art tools into the go you’d have to write otherwise.

func resetScores(players []Player) {
    for  _i, _ := range players {
        player := &players[_i]
        player.score = 0
    }
}

oh well

What’s annoying is the above broken form works if the array contains pointers. A lot of my code uses pointers, so I get used to writing the first form, and then it breaks when I do something different. Or I decide to optimize the code and reduce allocations by switching from []*Player to []Player without a careful audit of the impacted loops. Alas, I probably wouldn’t think to use the reference form even if available until it’s too late.

The common mistakes wiki lists the capture bug twice, but doesn’t mention this bug.

Posted 06 Nov 2023 21:24 by tedu Updated: 06 Nov 2023 21:24
Tagged: go

two hackers one keyboard two ways

There’s an amazing and famous scene of two hackers sharing a keyboard on NCIS, but it gets a lot of derision on the internet. What people don’t realize is that their mockery only reveals their own lack of skill. As everyone knows, a true hacker has mastered the art of dual wielding, and a keyboard that can be dual wielded by one might also be used by two hackers in tandem.

more...

Posted 31 Oct 2023 04:13 by tedu Updated: 31 Oct 2023 04:13
Tagged: programming software x11