DEV Community

Cover image for Avoiding malloc for Small Strings in C With Variable Length Arrays (VLAs)
Yair Lenga
Yair Lenga

Posted on • Originally published at Medium

Avoiding malloc for Small Strings in C With Variable Length Arrays (VLAs)

Many C programs allocate small temporary buffers using malloc(), even when the buffer only lives for the duration of a function call.

In many cases, stack allocation using VLAs can be significantly faster because it avoids allocator overhead and improves cache locality.

I wrote a deeper analysis including benchmarks and practical guidelines.

Full article (Medium — no paywall):
Using VLA for Faster Temporary Strings in C

The article proposes conditional logic: use a VLA when the requested size safely fits on the stack, and fall back to malloc() otherwise. Small macros hide the decision so the code remains compact and readable.

static void test1(bool show, const char *s1, const char *s2)
{
  // Create char *result - pointing to heap/stack
  FLEX_STR_INIT(result, strlen(s1) + strlen(s2) + 1);

  // Use the buffer
  concat(FLEX_STR_BUF(result), s1, s2)) ;
  printf("result(%zu)=%s\n", FLEX_STR_SIZE(result), result);

  // Release buffer (NOOP is VLA was used)
  FLEX_STR_FREE(result);
}

Enter fullscreen mode Exit fullscreen mode

For small strings this approach can reduce allocation overhead dramatically.

Top comments (0)