title: The relation of Stack, Memory Heap and assembly code
body: <p>I'm trying to understand the compilation process of a C/C++ code and it's memory management in more details. Assuming the following code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  int main() {
      int a = 5;
      int *b = (int *) malloc(40);
      return 0;
  }
  </code></pre>
  
  <p>I know <code>a</code> and <code>b</code> will be created on the stack and value of <code>b</code> (memory that it points to) will be on the heap. </p>
  
  <p>The code compiled to assembly will look like this:</p>
  
  <pre><code>    pushq   %rbp
      .cfi_def_cfa_offset 16
      .cfi_offset %rbp, -16
      movq    %rsp, %rbp
      .cfi_def_cfa_register %rbp
      subq    $16, %rsp
      movl    $40, %eax
      movl    %eax, %edi
      movl    $0, -4(%rbp)
      movl    $5, -8(%rbp)
      callq   _malloc
      xorl    %ecx, %ecx
      movq    %rax, -16(%rbp)
      movl    %ecx, %eax
      addq    $16, %rsp
      popq    %rbp
      retq
  </code></pre>
  
  <p>My Question is;</p>
  
  <p>What does <code>a is on the stack (memory)</code> mean here? according the above assembly, <code>a</code> is embedded directly into the instruction <code>$5, -8(%rbp)</code>, there is no reference to a memory location. If it IS on the memory then what's the address of <code>a</code>? </p>
  
  <p>I know <code>_malloc</code> creates 40 bytes on the heap (memory) and returns the first memory address but I cannot see how the stack gets populated, there is no interaction with the memory here other than the instructions themselves being fetched form it.</p>