1

I am trying to open a file using a C function, but it says that it cannot access some memory location.

.data

filename: .asciz "some.bmp"
write: .asciz "wb"

.global main

main:

mov filename , %rdi      # pass filename to rdi
mov write , %rsi         # pass opening mode to rsi
call fopen               # call fopen - seg faults

mov $0 , %rdi
call exit

I want to use C functions for educational purposes, I know I can open the file using syscalls.

Razvycs
  • 11
  • 3
  • 2
    Did you intend to use `$filename` and `$write`? (i.e. the addresses, rather than the values at those addresses). – Michael Oct 15 '18 at 10:11
  • "pass filename to rdi" - `fopen` wants nul terminated string pointer, not the string itself. You are loading 8 character into `rdi`, instead of address of first character. `mov $filename, %rdi` will load address instead, or `lea filename, %rdi`. Same issue with mode string usage, that's also `const char *` (memory address to C-string), not characters themselves. (check in debugger the difference, keep the current `mov filename,...` and add one more with `$` after it, and then see in debugger how they differ and how the `rdi` content is chars vs address.) – Ped7g Oct 15 '18 at 10:14
  • You want the addresses, not the memory contents, so use `lea filename(%rip), %rdi` or if you're going to link into a non-PIE executable, `mov $filename, %edi`. (see [Difference between movq and movabsq in x86-64](https://stackoverflow.com/q/40315803) for why RIP-relative `lea` is better than `movabsq $filename, %rdi`.) – Peter Cordes Oct 15 '18 at 14:54
  • Thank you for your replies! It makes sense to pass the address, not the value. I used that and it works now. – Razvycs Oct 15 '18 at 17:13

0 Answers0