Skip to main content
Be Bitwise
x86 AssemblyLinking & C Interop

Calling C from Assembly

The C standard library hands you hundreds of ready-made functions: printf, malloc, free, strlen, fopen, and on it goes. No sane person reimplements all that in assembly. You just call into libc. That's how most real assembly code looks in the wild — hot loops or low-level access live in asm, everything else borrows from C.

Using extern to Declare C Functions

To call into a C function, declare it extern and stick to the System V AMD64 calling convention.

nasm
extern printf
extern malloc
extern free
extern puts
section .data
fmt db "The answer is %d", 10, 0 ; printf format string (must be null-terminated)
section .text
global main ; use 'main' instead of '_start' when linking with libc
main:
; Set up stack frame (required for 16-byte alignment)
push rbp
mov rbp, rsp
; Call printf(fmt, 42)
lea rdi, [fmt] ; first arg: format string
mov rsi, 42 ; second arg: the integer value
xor eax, eax ; AL = 0 (no floating point args in XMM registers)
call printf
; Return 0 from main
xor eax, eax
leave
ret

Linking with GCC Instead of ld

Once libc is in play, you have to link through gcc (or cc) rather than calling ld directly. GCC pulls in the C runtime startup code and chains in libc for you.

bash
nasm -f elf64 program.asm -o program.o
gcc program.o -o program -no-pie # link with C library
./program

Two things shift from our earlier programs:

  1. Entry point becomes main, not _start. The C runtime owns _start now — it boots libc, then hands control to main.
  2. Linking goes through gcc, not ld. That pulls in the C runtime startup (crt0), libc itself, and all the dynamic linker plumbing.

Stack Alignment Before C Calls

The System V ABI demands a 16-byte aligned stack at the moment of a call. But call itself pushes an 8-byte return address, so the moment your callee starts running, the stack is misaligned by 8. A single push rbp puts it back on a 16-byte boundary.

nasm
main:
push rbp ; 8 bytes pushed -> stack now 16-byte aligned
mov rbp, rsp
; Stack is aligned. Safe to call C functions.
call some_c_function
leave
ret

Skip the alignment and any C function that touches SSE — that includes printf once a float shows up — segfaults instantly. It's the classic gotcha when you start mixing asm and C.

Aligned vs Misaligned Stack

x86-64
C Source
1main:
2 push rbp
3 mov rbp, rsp
4 ; Stack is 16-byte aligned
5 call printf
6 leave
7 ret
Assembly
1main:
2 ; NO push rbp
3 ; Stack is MISALIGNED (8 mod 16)
4 call printf ; CRASH on SSE
5 ret

Hover over code lines or mapping badges to see correspondences

Calling malloc and free

Heap allocation from assembly uses exactly the malloc and free you already know.

nasm
extern malloc
extern free
extern memset
section .text
global main
main:
push rbp
mov rbp, rsp
sub rsp, 16 ; space for local variables (maintains alignment)
; Allocate 256 bytes
mov rdi, 256 ; size in bytes
call malloc
test rax, rax ; check for NULL (allocation failure)
jz .alloc_failed
mov [rbp - 8], rax ; save pointer on stack
; Zero-fill the allocated memory
mov rdi, rax ; dest = allocated memory
xor esi, esi ; value = 0
mov rdx, 256 ; count = 256 bytes
call memset
; Use the memory...
mov rdi, [rbp - 8] ; load the pointer
mov qword [rdi], 0xDEADBEEF ; store a value
; Free the memory
mov rdi, [rbp - 8]
call free
xor eax, eax ; return 0
leave
ret
.alloc_failed:
mov eax, 1 ; return 1 (error)
leave
ret

The AL Register and Variadic Functions

For variadic functions like printf, System V wants AL to hold the count of floating-point arguments you've crammed into XMM registers.

nasm
; printf with no float args
lea rdi, [fmt_int] ; format string
mov rsi, 42 ; integer arg
xor eax, eax ; AL = 0: no float args
call printf
; printf with one float arg
lea rdi, [fmt_float]
movsd xmm0, [my_double] ; first float arg in xmm0
mov eax, 1 ; AL = 1: one float arg in XMM
call printf

Forget to set AL and you'll spend an afternoon debugging mysterious crashes. Set it. Always. Before any variadic C call.

Calling String Functions

The libc string functions are handy from assembly. They also come with all the same footguns they have in C — nothing about asm makes strcpy any safer.

nasm
extern strlen
extern snprintf
section .data
source db "Hello from C library!", 0
fmt_s db "%s", 0
section .bss
dest resb 32
section .text
; Get string length
lea rdi, [source]
call strlen
; rax = 21 (length not including null terminator)
; Bounded copy: snprintf(dest, 32, "%s", source)
lea rdi, [dest] ; destination
mov rsi, 32 ; full size of dest; snprintf always NUL-terminates
lea rdx, [fmt_s] ; fixed format string
lea rcx, [source] ; the data goes in as an argument
xor eax, eax ; variadic call: no vector registers used
call snprintf
; rax = length the full string would have had; >= 32 means it was truncated

You'll see strncpy offered as the "safe" strcpy, which flatters it: when the source is at least as long as the limit, strncpy stops without writing a NUL, so you have to terminate the buffer by hand every time. snprintf with a "%s" format always terminates (for any size above zero) and tells you when it truncated. On glibc 2.38 and later, strlcpy does the same job with less ceremony.

Preserving Registers Across C Calls

C functions are free to clobber RAX, RCX, RDX, RSI, RDI, R8, R9, R10, and R11 — those are the caller-saved registers. Need a value to survive a call? Stash it in a callee-saved register (RBX, R12-R15, RBP) or on the stack.

nasm
; BAD: assumes rdi still holds the string after the call
lea rdi, [msg1]
call puts ; puts may clobber rdi
call puts ; rdi is now whatever puts left behind
; FINE: reload rdi before each call
lea rdi, [msg1]
call puts
lea rdi, [msg1] ; reload from the label
call puts
; If the value can't be recomputed, keep it in a callee-saved register
mov r12, rdi ; save the pointer in r12
call some_function ; r12 survives this call
mov rdi, r12 ; restore
Format String Attacks When Calling printf

Passing user-controlled data as the format string to printf is one of the worst things you can do, in C or assembly. Hand an attacker control of the first argument and %x lets them peel back the stack, %n lets them scribble into arbitrary memory. Never let untrusted bytes become a format string. Use a fixed format and shovel user data into the trailing arguments.

Security Perspective: Format String Attacks

Format string attacks really click once you've seen them at the instruction level:

nasm
; SAFE: user input as a data argument
lea rdi, [safe_fmt] ; "%s\n"
lea rsi, [user_input] ; user data is an argument, not the format
xor eax, eax
call printf
; DANGEROUS: user input as the format string
lea rdi, [user_input] ; if user_input = "%x %x %x %n", disaster
xor eax, eax
call printf ; reads stack values, can write to memory

A %x in the format string tells printf to grab the next argument from a register or the stack. With no real arguments waiting, it just hoovers up whatever bytes happen to be sitting there — canary values, saved return addresses, anything. The %n specifier turns the leak into a write: it stores the count of characters printed so far into a pointer argument, which is how you get arbitrary memory writes.

The whole vuln lives in one mechanic. printf uses the format string itself to decide how many registers and stack slots to consume. Hand the attacker the format string, you've handed them the read and write primitive.

What is Next

Next up, the direction flips. Instead of asm calling into C, you'll embed asm inside C using GCC's inline assembly syntax.