1

I've been reading up on the x86 stack and the CDECL convention and read something that confused me.

Among the caller's responsibilities listed were popping the parameters, using them or simply incrementing %esp to remove them.

How does that last part work?

For example, say the initial value of %esp is 0x105000 and you decrement it by $0x1c for your current stack frame. You allocate some data, then increment it back - in that case wouldn't that data still float around in memory? How is the memory cleared? Would accessing 0x104FF4 lead to a segmentation fault and if so, what cleared the data there?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user8814
  • 94
  • 6
  • What do you think "clear" memory feels like? How do you "float" through memory? – Kerrek SB Jul 10 '14 at 00:22
  • Ehm, by 'clear' I suppose I meant for the bytes that were utilized to go back to a default value they held before being set to something else in the stack frame that was just popped - if such a default value even exists. And by 'float' I meant for those bytes to keep the value set in the popped frame. – user8814 Jul 10 '14 at 16:40
  • Sorry if I'm not making much sense, I'm still trying to figure out how the stack works and how it differs from the heap. I was just confused whether you would have to free the stack similar to the way you free an allocated structure in C - each element first, then the whole structure; or whether the OS did that for you; or whether you don't have to free it at all. – user8814 Jul 10 '14 at 16:43

1 Answers1

4

POP just moves data to a register and adjusts the stack pointer. It doesn't erase the data or have any other side effects.

So, if you don't need the data moved back to a register, then adjusting the stack pointer with ADD is all you need to do. You get the stack pointer back where you want it, only without having to clobber a register with a POP instruction.

It's also potentially more efficient. You will only ever need one ADD instruction rather than a series of POPs which might be slower or result in larger code.

The data does still exist in memory, but will be overwritten when you next push data to the stack.

JCx
  • 2,689
  • 22
  • 32