Question

NASM Assembly, Ubuntu, 32-bit program.

Normally, when popping a value from the stack, I'll do

POP somewhere

Into a register or a variable. But sometimes, I simply don't want to put it anywhere - I just want to get rid of the next element in the stack. Doing

POP

Just like that won't work.

A workaround I had was to make a 4-byte variable I don't use at all and dump the POP into it. Is there a better way to achieve this?

Was it helpful?

Solution

Adjust the stack pointer by four bytes (or some other amount), ignoring whatever value was on top:

add esp, 4

OTHER TIPS

As John Zwinck already pointed out, you can use add esp, 4 to effectively "pop into nowhere". And of course, you can use other constants to pop only a word (2), two dwords (8), or whatever.

If you want to not modify the arithmetic status flags, you may use lea esp, [esp + 4] instead. (This does not work for a 16-bit stack addressed by sp because [sp + immediate] cannot be encoded.)

If you have a stack frame created with ebp pointing at the base, you may get away with just mov esp, ebp to discard all the stack slots allocated since ebp was set. (Part of the operation of the leave instruction is effectively the same as mov esp, ebp.)

Likewise, you may change the stack pointer by using lea esp, [ebp - immediate] but that requires keeping track of how far ebp is from your desired esp value.

Finally, aside from popping into a scratch memory destination, you can always pop into registers that are not "in use", ie may be clobbered by your code at that point. For example, here I use pop cx twice just to get rid of the stack slots, which is shorter to encode than add sp, 4: https://hg.ulukai.org/ecm/ldosboot/file/b7cf0f0fee06/boot.asm#l1186

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top