From dd5b4a7ff2f09499f68110c28660d6731a64a80a Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Thu, 8 Jan 2026 20:21:13 +0000 Subject: [PATCH] perf: Use stack allocation in drawstatusbar Replaces heap allocation (malloc/free) with stack allocation for the status text buffer in the frequently called `drawstatusbar` function. The buffer is bounded by the global `stext` size (1024 bytes). Impact: - Reduces memory allocation overhead in the main drawing loop. - Eliminates potential malloc failure point. - Avoids heap fragmentation from small transient allocations. --- .jules/bolt.md | 3 +++ bar.c | 12 ++++-------- 2 files changed, 7 insertions(+), 8 deletions(-) create mode 100644 .jules/bolt.md diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 00000000..7e2746c7 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2026-01-08 - Stack Allocation in Hot Path +**Learning:** In C window managers, status bars are redrawn very frequently (every second or more). Allocating strings on the heap (`malloc`) for temporary buffers in these hot paths adds unnecessary overhead and fragmentation. +**Action:** For bounded strings (like status text which is often limited to 1024 bytes), use stack allocation. It's faster, safer (no memory leaks), and removes failure paths (`die("malloc")`). Always check bounds with `strncpy`. diff --git a/bar.c b/bar.c index 8476144a..e87ea24e 100644 --- a/bar.c +++ b/bar.c @@ -50,18 +50,15 @@ int drawstatusbar(Monitor *m, int bh, char *stext) { int i; int w; int x; - int len; int cmdcounter; short isCode = 0; - char *text; + char text_buf[1024]; + char *text = text_buf; char *p; - len = strlen(stext) + 1; - if (!(text = (char *)malloc(sizeof(char) * len))) { - die("malloc"); - } + strncpy(text, stext, sizeof(text_buf)); + text[sizeof(text_buf) - 1] = '\0'; p = text; - memcpy(text, stext, len); /* compute width of the status text */ w = 0; @@ -194,7 +191,6 @@ int drawstatusbar(Monitor *m, int bh, char *stext) { } drw_setscheme(drw, statusscheme); - free(p); return ret; }