2

This is a weird issue that I can't seem to find an answer to. This:

#include <iostream>
using namespace std;

void show_number(int number) {
    cout << number << endl;   // Shows '10' as expected
}

int main() {
    cout << endl; // Remove this and it fails

    __asm {
        mov rdi, 10
        call show_number
    }
}

actually works fine, except when you remove the initial cout << endl (first line of main). When you remove it, the cout in show_number seems to cause a segfault for some reason.

What causes this?

(OSX Mavericks x64, but should work in linux as well I think)

Cai
  • 3,609
  • 2
  • 19
  • 39
sircodesalot
  • 11,231
  • 8
  • 50
  • 83

1 Answers1

3

The Mac OS X ABI requires a 16-bytes stack alignment, before calling a function.

If your code is working, you're simply lucky, and this explains why you're getting e segmentation fault when modifying previous sections of the code.

So you need to ensure the stack is aligned on a 16-byte boundary.
I already answered a similar question a few times ago:

How to print argv[0] in NASM?

The interesting part is:

; Align stack on a 16 bytes boundary
mov     ebp,                esp
and     esp,                0xFFFFFFF0

Be sure to read the full answer, though...

Community
  • 1
  • 1
Macmade
  • 52,708
  • 13
  • 106
  • 123
  • I've heard that before, but I'm confused as to how to apply it. Can you show me a quick edit of my asm region to show how this should be done? – sircodesalot Apr 17 '14 at 16:08
  • See the edit, and read carefully my answer in the post in mentioned. – Macmade Apr 17 '14 at 16:17
  • Certainly appreciate the help, but something seems off. In fact, I can call functions all day long without having to worry about alignment, it only seems like `cout` has this problem. Any other function I call though seems to work fine. – sircodesalot Apr 17 '14 at 18:25
  • With more experience I now understand what you mean. Marked as accepted, thanks. – sircodesalot Oct 22 '15 at 10:54