Skip to content
HN On Hacker News ↗

How do functions like alloca allocate memory from the stack?

▲ 68 points 73 comments by ingve 6d ago HN discussion ↗

Pangram verdict · v3.3

We believe that this entire text is human-written.

0 %

AI likelihood · overall

Human
100% human-written 0% AI-generated
SEGMENTS · HUMAN 1 of 1
SEGMENTS · AI 0 of 1
WORD COUNT 274
PEAK AI % 0% · §1
Analyzed
Aug 17
backend: pangram/v3.3
Segments scanned
1 windows
avg 274 words each
Distribution
100 / 0%
human / AI fraction
Verdict
Human
Pangram v3.3

Article text · 274 words · 1 segments analyzed

Human AI-generated
§1 Human · 0%

A little while ago, I talked about how compilers ensure that large stack allocations do not skip over the guard page. Shawn Van Ness was curious how this works with _alloca. “Does it do the necessary _chkstk() probing?” Yes, the _alloca() function calls the same _chkstk() function to probe the stack before adjusting the stack pointer for the allocated memory. Here’s an artificial example: #include <malloc.h> void consume(void*,void*); void f(int n) { char buffer[16384]; consume(alloca(n), buffer); } On x86-64, this results in push rbp mov eax, 16416 ; probe for local frame call __chkstk sub rsp, rax ; create local frame lea rbp, [rsp+32] movsxd rax, ecx ; n lea rcx, [rax+15] ; round up to multiple of 16 and rcx, -16 mov rax, rcx ; special __chkstk calling convention call __chkstk sub rsp, rcx ; allocate n bytes lea rdx, [rbp] ; rdx -> buffer lea rcx, [rsp+32] ; rcx -> alloca'd memory call consume lea rsp, [rbp+16384] ; clean up local frame pop rbp ret 0 Observe that the same __chkstk function is used both for performing the initial stack probe when creating the local frame as well as for the alloca(). Author Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.