0

I have the following function:

int max(int num1, int num2)
{
    int retval;
    __asm__("maxii_start:;"
        "movl %1, %%eax;" 
        "subl $0, %%eax;" 
        "movl %2, %%edx;"
        "subl $0, %%edx;"
        "cmpl %%edx, %%eax;"
        "jle maxii0;"
        "addl $0, %%eax;"
        "jmp maxii1;"
        "maxii0:;"
        "movl %%edx, %%eax;"
        "maxii1:;"
        "movl %%eax, %0;"
        "ret;"
        :"=r"(retval)
        :"r"(num1), "r"(num2)
        );
    return retval;
}

When I use it, eg. like int m = max(5, 10); I see Segmentation fault (core dumped).

I think that there's sth incorrect with the way I use cmpl. What's wrong with this function?

1

1 Answer 1

2
  1. You need to let the compiler know what registers you are changing in the assembly code (called “clobbers”).

Before the closing parenthesis of the asm, add

: “eax”, “edx”

Actually it would be better to let the compiler choose the registers to use, but that would require rewriting the whole thing.

  1. Don’t put the “ret” in the asm statement. You need to let the compiler generate the function epilogue.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.