frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Allocating on the Stack

https://go.dev/blog/allocation-optimizations
52•spacey•3h ago

Comments

HarHarVeryFunny•1h ago
This article is about Go, but I wonder how many C/C++ developers realize that you've always had the ability to allocate on the stack using alloca() rather than malloc().

Of course use cases are limited (variable length buffers/strings, etc) since the lifetime of anything on the stack has to match the lifetime of the stack frame (i.e the calling function), but it's super fast since it's just bumping up the stack pointer.

ozgrakkurt•1h ago
This is more of a patch/hack solution as far as I can understand.

You can just as well pass a heap allocated buffer + size around and allocate by incrementing/decrementing size.

Or even better use something like zig's FixedSizeAllocator.

Correct me if I am wrong please

HarHarVeryFunny•44m ago
I wouldn't call it a hack, but it's not a general alternative for memory allocated on the heap since the lifetime is tied to that of the allocating function.

I think what you're referring to is an arena allocator where you allocate a big chunk of memory from the heap, then sequentially sub-allocate from that, then eventually free the entire heap chunk (arena) in one go. Arena allocators are therefore also special use case since they are for when all the sub-allocations have the same (but arbitrary) lifetime, or at least you're willing to defer deallocation of everything to the same time.

So, heap, arena and stack allocation all serve different purposes, although you can just use heap for everything if memory allocation isn't a performance issue for your program, which nowadays is typically the case.

Back in the day when memory was scarce and computers were much slower, another common technique was to keep a reuse "free list" of allocated items of a given type/size, which was faster than heap allocate and free/coalesce, and avoided the heap fragmentation of random malloc/frees.

rwmj•1h ago
Most C compilers let you use variable length arrays on the stack. However they're problematic and mature code bases usually disable this (-Werror -Wvla) because if the size is derived from user input then it's exploitable.
stackghost•59m ago
alloca()'s availability and correctness/bugginess is platform dependent, so it probably sees only niche usage since it's not portable. Furthermore, even its man page discourages its use in the general case:

>The alloca() function is machine- and compiler-dependent. Because it allocates from the stack, it's faster than malloc(3) and free(3). In certain cases, it can also simplify memory deallocation in applications that use longjmp(3) or siglongjmp(3). Otherwise, its use is discouraged.

Furthermore:

>The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.

https://man7.org/linux/man-pages/man3/alloca.3.html

spacechild1•58m ago
alloca() is super useful, but it's also quite dangerous because you can easily overflow the stack.

The obvious issue is that you can't know how much space is left on the stack, so you basically have to guess and pick an arbitrary "safe" size limit. This gets even more tricky when functions may be called recursively.

The more subtle issue is that the stack memory returned by alloca() has function scope and therefore you must never call it directly in a loop.

I use alloca() on a regular basis, but I have to say there are safer and better alternatives, depending on the particular use case: arena/frame allocators, threadlocal pseudo-stacks, static vectors, small vector optimizations, etc.

12_throw_away•27m ago
> The obvious issue is that you can't know how much space is left on the stack [...]

Oh, huh. I've never actually tried it, but I always assumed it would be possible to calculate this, at least for a given OS / arch. You just need 3 quantities, right? `remaining_stack_space = $stack_address - $rsp - $system_stack_size`.

But I guess there's no API for a program to get its own stack address unless it has access to `/proc/$pid/maps` or similar?

chuckadams•5m ago
[delayed]
norir•19m ago
If you have well defined boundaries, you can move the stack to an arbitrarily large chunk of memory before the recursive call and restore it to the system stack upon completion.
anematode•51m ago
If you're not doing recursion, I prefer using an appropriately sized thread_local buffer in this scenario. Saves you the allocation and does the bookkeeping of having one per thread
bertylicious•1h ago
Nice! That's (seems) so simple yet also so very effective. Shouldn't other memory-managed languages be able to profit from this as well?
lionkor•8m ago
C# has `stackalloc`
nasretdinov•53m ago
Nice to see common and natural patterns to have their performance improved. Theoretically appending to a slice would be possible to handle with just stack growth, but that would require having large gaps between goroutine stacks and mapping them lazily upon access instead of moving goroutines to the new contiguous blocks as it's implemented right now. But given how many questionable changes it requires from runtime it's certainly not going to happen :)
ivanjermakov•40m ago
Having big stack frames is bad for cache locality. Stack is not something magical, it's mapped to the same physical memory as heap and needs to be loaded. Pretty sure such optimization would reduce performance in most cases.
anematode•49m ago
Awesome stuff! Does Go have profile-guided optimization? I'm wondering whether a profile could hint to the compiler how large to make the pre-reserved stack space.
tptacek•34m ago
Yep. `go build -pgo=foo.pprof`

https://go.dev/doc/pgo

zabzonk•42m ago
alloca() is not part of the C++ standard, and I can't imagine how it could used safely in a C++ environment
mwkaufma•26m ago
If I had a nickel for every article about avoiding implicit boxing in gc-heap languages...

Dan Simmons, author of Hyperion, has died

https://www.dignitymemorial.com/obituaries/longmont-co/daniel-simmons-12758871
114•throw0101a•1h ago•37 comments

A better streams API is possible for JavaScript

https://blog.cloudflare.com/a-better-web-streams-api/
261•nnx•5h ago•96 comments

Allocating on the Stack

https://go.dev/blog/allocation-optimizations
53•spacey•3h ago•19 comments

Writing a Guide to SDF Fonts

https://www.redblobgames.com/blog/2026-02-26-writing-a-guide-to-sdf-fonts/
12•chunkles•1h ago•0 comments

We gave terabytes of CI logs to an LLM

https://www.mendral.com/blog/llms-are-good-at-sql
107•shad42•3h ago•69 comments

Don't run OpenClaw on your main machine

https://blog.skypilot.co/openclaw-on-skypilot/
34•hopechong•1h ago•22 comments

Modeling Cycles of Grift with Evolutionary Game Theory

https://www.oranlooney.com/post/grifters-skeptics-marks/
38•ibobev•3d ago•12 comments

Kyber (YC W23) Is Hiring an Enterprise Account Executive

https://www.ycombinator.com/companies/kyber/jobs/59yPaCs-enterprise-account-executive-ae
1•asontha•57m ago

Tenth Circuit: 4th Amendment Doesn't Support Broad Search of Protesters' Devices

https://www.eff.org/deeplinks/2026/02/victory-tenth-circuit-finds-fourth-amendment-doesnt-support...
301•hn_acker•4h ago•37 comments

Get free Claude max 20x for open-source maintainers

https://claude.com/contact-sales/claude-for-oss
266•zhisme•10h ago•139 comments

Show HN: RetroTick – Run classic Windows EXEs in the browser

https://retrotick.com/
140•lqs_•6h ago•39 comments

Sprites on the Web

https://www.joshwcomeau.com/animation/sprites/
71•vinhnx•3d ago•14 comments

Show HN: Badge that shows how well your codebase fits in an LLM's context window

https://github.com/qwibitai/nanoclaw/tree/main/repo-tokens
66•jimminyx•4h ago•39 comments

F-Droid Board of Directors nominations 2026

https://f-droid.org/2026/02/26/board-of-directors-nominations.html
139•edent•9h ago•83 comments

What was the first life restoration of a sauropod?

https://svpow.com/2026/02/02/what-was-the-first-life-restoration-of-a-sauropod/
13•surprisetalk•2d ago•3 comments

Statement from Dario Amodei on our discussions with the Department of War

https://www.anthropic.com/news/statement-department-of-war
2747•qwertox•20h ago•1461 comments

Experts sound alarm after ChatGPT Health fails to recognise medical emergencies

https://www.theguardian.com/technology/2026/feb/26/chatgpt-health-fails-recognise-medical-emergen...
137•simonebrunozzi•3h ago•105 comments

NASA announces major overhaul of Artemis program amid safety concerns, delays

https://www.cbsnews.com/news/nasa-artemis-moon-program-overhaul/
85•voxadam•3h ago•91 comments

The Hunt for Dark Breakfast

https://moultano.wordpress.com/2026/02/22/the-hunt-for-dark-breakfast/
471•moultano•15h ago•171 comments

Your device identity is probably a liability

https://smallstep.com/blog/ncsc-zero-trust-device-identity/
11•eustoria•1h ago•2 comments

Debian Removes Free Pascal Compiler / Lazarus IDE

https://forum.lazarus.freepascal.org/index.php?topic=73405.0
50•mariuz•2d ago•21 comments

Show HN: Unfudged – version every change between commits - local-first

https://www.unfudged.io/
19•cyrusradfar•22h ago•14 comments

An interactive intro to quadtrees

https://growingswe.com/blog/quadtrees
171•evakhoury•3d ago•20 comments

Can you reverse engineer our neural network?

https://blog.janestreet.com/can-you-reverse-engineer-our-neural-network/
225•jsomers•2d ago•150 comments

Open source calculator firmware DB48X forbids CA/CO use due to age verification

https://github.com/c3d/db48x/commit/7819972b641ac808d46c54d3f5d1df70d706d286
31•iamnothere•3h ago•16 comments

Breaking Free

https://www.forbrukerradet.no/breakingfree/
151•Aissen•9h ago•27 comments

Compact disc story (1998)

https://www.researchgate.net/publication/294484774_Compact_disc_story
45•pipeline_peak•16h ago•16 comments

Vibe coded Lovable-hosted app littered with basic flaws exposed 18K users

https://www.theregister.com/2026/02/27/lovable_app_vulnerabilities/
88•nottorp•2h ago•27 comments

Theory of Constraints: "Blue Light" creating capacity for nothing (2007)

http://theoryofconstraints.blogspot.com/2007/06/toc-stories-2-blue-light-creating.html
12•strongpigeon•1h ago•1 comments

Block spent $68M on a single party in September 2025

https://twitter.com/BullTheoryio/status/2027250361816486085
76•kappi•1h ago•49 comments