Assembly: Why does jumping to a label that returns via ret cause a segmentation fault?
Asked Answered
G

1

6

Linux Assembly Tutorial states:

there is one very important thing to remember: If you are planning to return from a procedure (with the RET instruction), don't jump to it! As in "never!" Doing that will cause a segmentation fault on Linux (which is OK – all your program does is terminate), but in DOS it may blow up in your face with various degrees of terribleness.

But I cannot understand why does it causes a segmentation fault. it sounds just like returning from a function.

I have a situation where I need to implement the logic "If X happens, call procedure A. Otherwise, call procedure B." Is there any other way than jumping around like a kangaroo weaving spaghetti code?

Greenhorn answered 23/3, 2012 at 23:22 Comment(3)
Just a note: there's nothing specifically preventing you from doing this, but what it does is not always obvious to new assembly programmers. The most common case of this is called a "tail call", and it's common in functional languages. The effect is to return to the caller of the function containing the jump (bypassing the rest of that function), if you've cleaned up your little part of the stack. If you haven't, that's when you see segfaults.Baptista
Make sure you understand the difference of jmp and call.Chantay
Related: call subroutines conditionally in assembly / What if there is no return statement in a CALLed block of code in assembly programs / JMP vs. CALL in 8086 assemblyGrenadier
L
10

Because CALL pushes the current instruction address onto the stack, and RET pulls it off in order to get back to the call-site. JMP (and related instructions) don't push anything onto the stack.

Lagging answered 23/3, 2012 at 23:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.