r/cprogramming • u/Yairlenga • Mar 10 '26
Avoiding malloc for Small Strings in C With Variable Length Arrays (VLAs)
https://medium.com/@yair.lenga/avoiding-malloc-for-small-strings-in-c-with-variable-length-arrays-vlas-7b1fbcae7193Temporary strings in C are often built with malloc.
But when the size is known at runtime and small, a VLA can avoid heap allocation:
size_t n = strlen(a) + strlen(b) + 1 ;
char tmp[n];
snprintf(tmp, n, "%s%s", a, b);
This article discusses when this works well. Free to read — not behind Medium’s paywall
5
Upvotes
12
u/tstanisl Mar 10 '26
This code relies on 0-length arrays which is not a part of standard C.
2
u/tstanisl Mar 10 '26
You should consider using pointer to the whole array to bind the array's size to the array itself.
Works like charm, see godbolt.
1
u/imaami Mar 10 '26
Instead of VLAs, you could implement an SSO string object.
1
u/No-Concern-8832 Mar 10 '26
In the past, we would use alloca() to allocate memory on the stack, if we're sure it would fit without overflow. Back then, some C runtimes only allocate 2KB to 4KB of stack space for each function call. Is VLA stack safe?
1
u/edgmnt_net Mar 11 '26
Although if you can, you should probably consider designing APIs around stuff that makes handling such strings easier. Not always an option, but just saying that if you get to the point where you need to compute those lengths and move all the stuff, some opportunity has already been lost. You can have better representations for strings, better ways to represent operations like concatenation and so on. At least theoretically.
1
u/Tcshaw91 Mar 14 '26
If you know the lifetime of the temp string you can also just make an allocator tied to that lifetime. Like if the string only lasts for a frame you could just use an arena. No need for VLAs
1
u/zhivago Mar 14 '26
You should understand that VLAs are not required to be stack allocated.
This is one reason why longjmp is not required to deallocate them.
3
u/[deleted] Mar 10 '26
[removed] — view removed comment