Reputation:
Consider the following line:
int v[100];
This line allocates 100*sizeof(int)
memory bytes. But if we're looking for disassembly of this line then there is no code behind it. So does memory allocation executed with no machine instruction? I'm confused...
Upvotes: 1
Views: 121
Reputation: 129524
In the compiler, local variable allocations are turned into alloca
(or "stack allocation"), which is, assuming the variable isn't "unused and completely removed", typically done by subtracting the total size needed from the stack pointer at the beginning of the function, and added back on (or otherwise restoring stack pointer) at the end of the function.
This is the "LLVM IR" (IR = Intermedia Representation) for a function like the one described above:
define i32 @fn() #0 {
%v = alloca [100 x i32], align 16
ret i32 42
}
In x86-64 assembler, it becomes:
fn: # @fn
pushq %rbp
movq %rsp, %rbp
subq $272, %rsp # imm = 0x110
movl $42, %eax
addq $272, %rsp # imm = 0x110
popq %rbp
retq
(Don't ask my why it is 272 bytes, rather than 400 - I really have no idea!)
If we enable optimisation, with -O2, it becomes:
fn: # @fn
.cfi_startproc
movl $42, %eax
retq
In other words, the stack allocation goes away completely.
Source code:
int fn()
{
int v[100];
return 42;
}
Upvotes: 0
Reputation: 36906
It depends on the context, but you are most likely talking about stack allocated memory / auto variables, like this:
int fn()
{
int v[100];
...
}
If you look at the disassembly of fn
, you should notice in the function prologue that some value is subtracted from esp
register.
For example,
sub esp, 190h
This is the allocation you're looking for. That variable is stored on the stack, so by moving the stack pointer, esp
, you have cleared room for it.
Upvotes: 5