0

Compiling a simple C code into assembly using GCC will have the following output:

... 13 xorl %eax, %eax 14 movl $0, -4(%rbp) 15 movl $5, -8(%rbp) 16 movl $6, -12(%rbp) 17 movl -8(%rbp), %ecx 18 addl -12(%rbp), %ecx 19 movl %ecx, -16(%rbp) 20 popq %rbp 21 retq 

My question is, why an offset to the frame base pointer (rbp) is being used instead of manipulating the stack pointer (rsp). Isn't that the whole point of having a stack pointer?

What if the stack of this process gets overwritten by some other process (Garbage collection as an example) which doesn't even know the stack is being used, since rsp isn't decremented when writing values.

6
  • 1
    The stack pointer allows you to manipulate data as you use it. If you want to have variables that persist for an entire scope, that's the point of the stack frame. You make space on the stack (or not if it fits in the red zone, and you don't call anything), and manipulate data relative to the frame pointer. Commented Jul 24, 2019 at 15:10
  • re: using space below RSP: Why is there no "sub rsp" instruction in this function prologue and why are function parameters stored at negative rbp offsets? And no, garbage-collection doesn't happen on stack memory. Plus, this is C compiler output so code-gen isn't assuming any kind of garbage collection! Commented Jul 24, 2019 at 15:22
  • IDK, it's not a bad question other than perhaps lack of research effort. I was already looking for appropriate duplicates; there are several. Note that gcc -O2 implies -fomit-frame-pointer which avoids wasting instructions making a stack frame. Use gcc -O3 (with maybe -fno-tree-vectorize) if you want efficient code to read. Wondering why un-optimized / debug-mode code is inefficient doesn't make much sense. Commented Jul 24, 2019 at 15:22
  • 1
    @ecm: I think you based your edit on the original, overwriting my tag edit. The appropriate tag for the call stack specifically is [callstack]. The [stack] tag usage guidelines say this; it's for generic stack data structures. Commented Jul 24, 2019 at 15:46
  • @Peter Cordes: Thanks, I'll keep that in mind. Commented Jul 24, 2019 at 16:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.