I have a simple c++ code as the following:
#include <iostream>
int main() {
int a = 5;
int *b = (int *) malloc(40);
return 0;
}
Setting a breakpoint using GDB on line 5 and running disas
will output the following:
Dump of assembler code for function main():
0x0000000100000f60 <+0>: push %rbp
0x0000000100000f61 <+1>: mov %rsp,%rbp
0x0000000100000f64 <+4>: sub $0x10,%rsp
0x0000000100000f68 <+8>: mov $0x28,%eax
0x0000000100000f6d <+13>: mov %eax,%edi
0x0000000100000f6f <+15>: movl $0x0,-0x4(%rbp)
0x0000000100000f76 <+22>: movl $0x5,-0x8(%rbp)
=> 0x0000000100000f7d <+29>: callq 0x100000f90
0x0000000100000f82 <+34>: xor %ecx,%ecx
0x0000000100000f84 <+36>: mov %rax,-0x10(%rbp)
0x0000000100000f88 <+40>: mov %ecx,%eax
0x0000000100000f8a <+42>: add $0x10,%rsp
0x0000000100000f8e <+46>: pop %rbp
0x0000000100000f8f <+47>: retq
Here are my questions:
1- Is all the stack needed for my app within this output? if I'm not mistaking the stack is pointed by rbp
and moves down?
2- b
is on the heap correct? I can see the address of it using x b
.
3- Why does x a
result in an error Cannot access memory at address 0x5
? is it because 5 isn't actually anywhere on the memory? I can see it's part of the instruction movl $0x5,-0x8(%rbp)
Edit (more questions):
4- I have read that int a = 5;
means variable a
is created on the stack (memory) with the value 5, is this correct? when I look at the generated assembly, the value 5
is directly within the instruction set (movl $0x5,-0x8(%rbp)
, there is no reference to a memory location. If it IS on the memory then how can I see it's memory address? if it is NOT then why do I read that a
is on the stack (memory)?
5- I know heap is also on the memory, is it visible from the above assembly?
6- I guess my biggest confusion and question is the relation between memory management and generated assembly, can I always point out what/where the heap/stack are given a assembly code? if not what else is needed?
Best Answer
This question is somewhat ill-formed as written. Because your app is only a single function, all variables in the
main()
function are on the stack shown here. However, your app was likely built with some indicator of what its stack size should be and the OS allocated that much stack for your application, even if you didn't use all of it.The
rbp
andrsp
registers work in concert to keep data and return addresses and values on the stack.The variable
b
is on the stack, but the memory that it points to, which you allocated withmalloc()
is on the heap.Note that the
x
command expects its argument to be an address. When you sayx b
you're saying you want gdb to show the memory pointed to byb
. When you sayx a
you're saying you want gdb to show the memory pointed to bya
. Buta
isn't a pointer. Thex
command is attempting to show you memory at address 5, which is a non-readable page of memory, so you get an error.