Segmentation fault when calling printf from C function called from assembly
You're not maintaining stack alignment. The ABI says that %rsp
must always be a multiple of 16 right before a call
instruction. call
itself pushes one 8-byte quantity (the return address), so the stack pointer is always congruent to 8 (mod 16) at function entry, and it's your responsibility to fix that before you make another call.
This only causes a crash when the call to fprintf
is uncommented because fprintf
is actually doing something that takes advantage of this ABI requirement (specifically, using some of the x86-64 vector instructions, probably to accelerate binary-to-decimal conversion). partition
by itself doesn't do anything that cares.
The easiest way for you to fix it will be to junk the frame pointer. It's not required on x86-64 and that way you will be pushing an odd number of registers, which gives you the proper stack alignment as a side effect.
Segmentation fault when using printf in nasm 64bit
Ok, i got it.
It turns out i need to add after main
:
push rbp
mov rbp, rsp
So the code looks like this:
section .data
_DATA1 db "aa", 0
section .text
global main
extern printf
main:
push rbp
mov rbp, rsp
sub rsp, 16
lea r13, [_DATA1]
mov rdi, r13
call printf
add rsp, 16
mov rax, 0
mov rsp, rbp
pop rbp
ret
I realise that this is also what gcc do
Related Topics
How to Exclude a Directory When Using 'Find'
Get Exit Code of a Background Process
How to Use Sed to Change My Configuration Files, With Flexible Keys and Values
How to Delete a Newline If It Is the Last Character in a File
How to Get Cmake to Find My Alternative Boost Installation
Why Does /Bin/Sh Behave Differently to /Bin/Bash Even If One Points to the Other
How to Determine If a Process Runs Inside Lxc/Docker
Pipe Only Stderr Through a Filter
How to Run a Script At a Certain Time on Linux
How to Store a Command in a Variable in a Shell Script
How to Pass the Password to Su/Sudo/Ssh Without Overriding the Tty
What Does "&" At the End of a Linux Command Mean
Get Destination Address of a Received Udp Packet
How to Compile a 32-Bit Binary on a 64-Bit Linux Machine With Gcc/Cmake
Error When Using Git Credential Helper With Gnome-Keyring as Sudo