You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

汇编中movl指令偏移量-4/-8/-12的作用及按4递增原因咨询

Understanding Stack Frame Offsets in x86 Assembly

Great question—let's unpack this piece by piece, since connecting C code to its assembly output is a great way to grok how your program uses memory under the hood.

What does -4 do in movl $1, -4(%rbp)?

First, let's recall that %rbp is the base pointer—think of it as an anchor pointing to the base of the current function's stack frame (the starting point of the stack space allocated for the function). On x86 systems, the stack grows downward (toward lower memory addresses).

The syntax -4(%rbp) means: take the address stored in %rbp, subtract 4 bytes from it, and use that resulting address as the target for the movl instruction. So this line is simply storing the value 1 in a memory location 4 bytes below the stack frame's base—this is almost always a local variable from your C code.

Why -4, -8, -12 for int x=1; int y=2; int z=3;?

Each of those offsets corresponds to the memory location allocated for your three int variables:

  • x gets stored at %rbp - 4
  • y gets stored at %rbp - 8
  • z gets stored at %rbp - 12

The compiler is reserving space for each local variable in the stack frame, placing them one after another starting from the base pointer and moving downward (since stack grows down). Each offset is 4 bytes apart because each variable needs its own chunk of memory that doesn't overlap with the others.

Why do offsets increase by 4? Is it because 4 bytes = 32 bits?

Bingo! On nearly all modern systems, the int data type is defined as a 32-bit signed integer. Since 1 byte = 8 bits, 32 bits works out to exactly 4 bytes. The compiler has to allocate 4 full bytes for each int to fit its entire range of values, so each subsequent variable is placed 4 bytes further down the stack.

As a side note: if you were using a larger type like long long (which is 64 bits, or 8 bytes), you'd see offsets increasing by 8 instead. But for int, 4 bytes is the standard size that matches its 32-bit width.

内容的提问来源于stack exchange,提问作者JackOfAll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:53:10