0

I am new to assembly programming. I am trying to do a simple thing which is read input from the terminal. I want to use fgets to do so. However I am facing a problem when trying to read multiple times.

I have been trying to solve it for a couple days now with no idea why the problem is occuring. I've tried debugging the program, but it crashes outside the code I wrote, so I have no clue what I did wrong.

The thing that makes it even more weird is that if I input less than 7 letters, I can do it as many times as I wish and the program works as I want it to. However the moment I input a 7th letter (or 8th if we count null-terminating char) the program works fine the first time, but on the next call it gives me a "Segmentation fault (core dumped)" error. I know this is an odd problem but I have no clue why it happens.

The following code is a very primative version of what I have but the exact same problem still occurs.

.data
buffer: asciz ""

.text
.global main
main:
call test
call test
call test

.global test
test:
movq $buffer, %rdi  #the buffer to save to
movq $10000, %rsi   #the number of letters I want
movq stdin, %rdx    #where to read from (terminal)
call fgets    

Any help is appreciated, Thanks!

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
TBB
  • 3
  • 2
  • Is this the actual code you are testing? It has several bugs, but I'm not sure whether they are in your actual code, or typos introduced in your "primitive version". – Nate Eldredge Sep 26 '21 at 18:29
  • 1
    Summary of what I've seen so far: (1) insufficient space reserved for `buffer`, (2) functions don't return, (3) `movq stdin, %rdx` should be `$stdin` (4) no [stack alignment](https://stackoverflow.com/questions/49391001/why-does-the-x86-64-amd64-system-v-abi-mandate-a-16-byte-stack-alignment) when calling `fgets` (though I think by chance it happens to work out, because of the extra `call` in between) – Nate Eldredge Sep 26 '21 at 18:31
  • this is the actual code im testing. If there is anything that I am doing wrong when writing please tell me, as I said I'm very new to this. But from the documentation im reading this seems fine. (the ret thing I missed) – TBB Sep 26 '21 at 18:31
  • 1
    @NateEldredge: I think `movq stdin(%rip), %rdx` is actually correct. It's a `FILE *stdin` global variable (unless it's a macro?), not `FILE stdin`, and stdio functions want the `FILE*` pointer value, not a `FILE **` address of a pointer. Your other points are right, with the crash happening either from stack alignment or after falling off the end of `test`, unless it happens to fall into something that returns. – Peter Cordes Sep 26 '21 at 18:39
  • @PeterCordes: Oh yes, you're right. Thanks. – Nate Eldredge Sep 26 '21 at 18:42
  • @NateEldredge thank you! your advice helped! I had not thought about the stack alignment or the buffer space. Turns out the thing causing the segfault is me writing outside of the space assigned to my buffer. – TBB Sep 26 '21 at 21:52

0 Answers0